最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't setTimeout(.., 0) execute immediately? - Stack Overflow

programmeradmin2浏览0评论
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
Add a ment  | 

1 Answer 1

Reset to default 7

Javascript 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

发布评论

评论列表(0)

  1. 暂无评论