The following interview question explores the use of
setTimeout with a delay of 0 seconds, also known as a “zero timeout.”
Consider the code snippet and find out what would be printed to the console.
Code snippet as a picture
What if we call
setTimeout(func, delay)takes a function
funcand delays its execution by
It may seem that if we set the delay to
0, then the function will be executed immediately, but it’s not the case.
The function will be placed in the message queue to run asynchronously. This will happen only after the current synchronous execution is done.
console.login the second line is a part of the synchronous execution and will run before the
console.login the first line.
In most web browsers
setTimeout(f, 0)has a delay of approximately 3 ms which is determined by the speed of internal processing.
plain logwill be printed first and then the message
timeout logwill follow.