admin管理员组文章数量:1357225
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
本文标签: javascriptWhy doesn39t setTimeout(0) execute immediatelyStack Overflow
版权声明:本文标题:javascript - Why doesn't setTimeout(.., 0) execute immediately? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744002777a2574166.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论