Skip to content Skip to sidebar Skip to footer

Why Does A Settimeout Delay Of 0 Still Run After All Other Synchronous Code In A For Loop?

I've know versions of this question has been discussed, and I think this is unique. Why does a delay of 0, still causes the below behavior. for(var i = 0; i <3; i ++) { cons

Solution 1:

JavaScript, both in the browser and on the server, runs as an event loop. The runtime is constantly polling for events. Events consist of user actions (e.g. DOM element x was clicked), I/O (data came back from I/O or ajax call), and timer events (in this case). setTimeout(fn, 0) simply adds an event to be processed by the event loop at minimum when 0 milliseconds have elapsed. It will always execute after the current event has been processed.

Solution 2:

Am I correct in saying the for-loop and any synchronous code is placed on the call stack before setTimeout

To be pedantic, setTimeout() itself gets called synchronously, and placed on the callstack right after console.log(i, 'started'); . It's the settimeout callback (in your case console.log(i)) that gets queued and called asynchronously.

Post a Comment for "Why Does A Settimeout Delay Of 0 Still Run After All Other Synchronous Code In A For Loop?"