I have a setTimeout call with 0 ms as time interval like show below, would the setTimeout execute immediately?
setTimeout(() => {
console.log('I am first.');
}, 0);
I have a setTimeout call with 0 ms as time interval like show below, would the setTimeout execute immediately?
setTimeout(() => {
console.log('I am first.');
}, 0);
No!! But it will execute as soon as the possible. The specified amount of time or the delay is not the guaranteed time to execution, but rather the minimum time to execution. So zero ms will execute as soon as the stack is empty.
The setTimeout with interval 0 ms does not execute immediately. To understand the concept, please follow the code below,
// event loop example
// setTimeouts will land in the a queue (FIFO) via WebAPI environment, which is part of the event loop
setTimeout(() => {
console.log('I am first.');
}, 0);
setTimeout(() => {
console.log('I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!');
}, 0);
setTimeout(() => {
console.log('Even, I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!');
}, 0);
// JavaScript statements land in the call stack (LIFO)
console.log('I will execute first because I am in the JavaScript environment call stack!');
Output:
I will execute first because I am in the JavaScript environment call stack!
I am first.
I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!
Even, I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!
Reference: Timeouts and intervals