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
为什么内部指令不首先执行,尽管将 setTimeout 时间设置为 0?我使用了各种时间,包括 0/null,我想知道如何保留 setTimeout 对象并随流程执行其指令。
最佳答案
Javascript 代码只在一个线程上运行。 setTimeout
安排函数稍后运行。所以在 js 中,当所有当前运行的代码完成执行时,event
循环将寻找任何其他事件。
所以 setTimeout( .. 0)
将使代码在当前循环之后运行。
console.log("I'm message from outside timeout");
将首先安排执行。一旦它完成 setTimeout
将被执行
所以底线 setTimeout(myfunction ,0)
将在当前执行函数后 0ms 运行 myfunction。 &在你的情况下,当前的执行循环是
console.log("I'm message from outside timeout");
如果再添加一个console.log("I'm message from outside timeout1"); 所以当前事件循环将首先记录
I'm message from outside timeout
I'm message from outside timeout1
在开始 setTimeout
函数之前。
注意 setTimeout
的最小超时为 4 毫秒。你可以看看这个Stackoverflow thread了解更多
关于javascript - 为什么 setTimeout(.., 0) 不立即执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904773/