setTimeout(function(){
console.log("m");
}, 0);
console.log("s");
Why does this code print "s"
before "m"
, even if the setTimeout
callback is supposed to wait for 0 ms?
setTimeout(function(){
console.log("m");
}, 0);
console.log("s");
Why does this code print "s"
before "m"
, even if the setTimeout
callback is supposed to wait for 0 ms?
A browser or node.js always run a single threaded event loop to run your code. On the first run it will always run your synchronous code but may also que up asynchronous events that will call back later. Thats why we call the function here callback function
it will be called later.
setTimeout
is a microtask.
That means the function
that you see isnt gona executed immedantly, it is gonna first queued up and will be executed within the next event loop.
Also a sidefact: 0 ms
just means it will minimum wait 0 ms
not exact 0
When you create a promise, or call an async function, or set a timeout for 0 milliseconds, the function is immediately queued into the Javascript event loop. Essentially, the function is added to a queue of functions to call, and once the javascript interpreter has nothing to do it'll start calling those functions. So, when you set a timeout for 0 milliseconds, it queues the console.log("m")
, then calls the console.log("s")
, then it has nothing to do so it finishes the queued console.log("m")
, which is why it's out of order.
it just because JS is single-threaded and event loop works that way. setTimeout has written in a way that it will send you function or whatever you want to do in a callback queue. and then move forward to the next line, once next line executed it will not run your setTimeout part, or in other words, it will not process the setTimeout part until the stack is not empty.
so this is your code, and it will execute like this.
setTimeout(function () {
console.log("m");
} , 0)
console.log('s');
maybe it's confusing by words, let's see this in action. I bet you can not get a better example than this to understand it, it's explained in the best way by Philip robert.
because JS code goes in order one by one. When you specifying setTimeout to 0 is still waiting, in C++ lang this would be something like this 0.000000245ms, and JS runs often on C++/C browser.
try this simple example
for (let x = 0; x < 500; x++) {
setTimeout(() => console.log(x), 0);
}
console.log('hello');