Zero setTimeout in JavaScript [Tech Interview Quiz]
The setTimeout
function is a commonly used JavaScript method that allows you to delay the execution of a piece of code for a specified amount of time. It is often used to create timers, animations, and other types of asynchronous tasks.
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
with 0 delay in JavaScript? Which of the messages will be printed first? (think well, then click for the answer and explanation)
Explanation
In JS,
setTimeout(func, delay)
takes a functionfunc
and delays its execution bydelay
milliseconds.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.
The
console.log
in the second line is a part of the synchronous execution and will run before theconsole.log
in 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.
Answer
The message
plain log
will be printed first and then the messagetimeout log
will follow.