-3

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);
Rajkumar M
  • 155
  • 10
  • 1
    Short answer, "no, it will execute after at least 0ms, but it might never execute". Longer answer, I would recommend watching this [talk by Jake Archibald](https://www.youtube.com/watch?v=cCOL7MC4Pl0) – Olian04 Jul 25 '20 at 11:13
  • recommended reading here: https://medium.com/javascript-in-plain-english/you-dont-know-javascript-until-you-can-beat-this-game-aa7fd58befb – Robin Zigmond Jul 25 '20 at 11:22

2 Answers2

1

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.

Pius T.K
  • 351
  • 5
  • 9
  • I agree and a good explanation. – Rajkumar M Jul 25 '20 at 11:25
  • 1
    "So zero ms will execute as soon as the stack is empty." this is not true. Well, it is more complex process then that. For example promise resolution will be executed before timeout. Not too speak about runtime specific things like DOM events in browser or system events in node. So it is not just "when call stack is empty". – Yury Tarabanko Jul 25 '20 at 11:29
-1

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

Rajkumar M
  • 155
  • 10
  • 2
    You answered your own question at the same time as you asked it... why? This is a common concept and there are already dozens of learning resources explaining it. – Olian04 Jul 25 '20 at 11:15
  • I thought, I figured a simple example to explain the concept. If you find the answer repetitive, please let me know. – Rajkumar M Jul 25 '20 at 11:19