var timeout = setTimeout(function(){
console.log("I'm message from timeout");
},0);
console.log("I'm message from outside timeout");
//1. I'm message from outside timeout
//2. I'm message from timeout
Why the inner instructions don't execute first, despite setting setTimeout time on 0? I use various times including 0/null and I'm wondering how to both retain setTimeout object and execute its instructions with the flow.
var timeout = setTimeout(function(){
console.log("I'm message from timeout");
},0);
console.log("I'm message from outside timeout");
//1. I'm message from outside timeout
//2. I'm message from timeout
Why the inner instructions don't execute first, despite setting setTimeout time on 0? I use various times including 0/null and I'm wondering how to both retain setTimeout object and execute its instructions with the flow.
Share Improve this question edited Apr 28, 2016 at 3:39 user2864740 62.1k15 gold badges158 silver badges227 bronze badges asked Apr 28, 2016 at 3:32 PawełPaweł 4,5366 gold badges25 silver badges42 bronze badges 4- 3 setTimeout always is deferred until the next "execution time" of JavaScript. A value of 0/null does not change this (and is treated as a value of 5 in modern browsers). – user2864740 Commented Apr 28, 2016 at 3:35
- 3 I wrote a long answer here: stackoverflow./questions/32580940/… and there are likely many other related questions – user2864740 Commented Apr 28, 2016 at 3:38
- stackoverflow./questions/9647215/… – user2864740 Commented Apr 28, 2016 at 3:40
- You should check this out: youtube./watch?v=8aGhZQkoFbQ – Crisoforo Gaspar Commented Apr 28, 2016 at 3:52
1 Answer
Reset to default 7Javascript code runs only on one thread. setTimeout
schedules a function to run later. So in js when all currently running code finish its execution , event
loop will look for any other event.
So setTimeout( .. 0)
will make code run after the current loop.
console.log("I'm message from outside timeout");
will be first scheduled to executued. As soon as it finish the setTimeout
will be executed
So bottom line setTimeout(myfunction ,0)
will run myfunction 0ms after currently executing function. & in your case the current execution loop is
console.log("I'm message from outside timeout");
If you add another console.log("I'm message from outside timeout1"); so current event loop will first log
I'm message from outside timeout
I'm message from outside timeout1
before starting setTimeout
function.
NOTE setTimeout
has a minimum timeout of 4ms . You can look at this Stackoverflow thread to know more about it