【问题标题】:Why doesn't setTimeout(.., 0) execute immediately?为什么 setTimeout(.., 0) 不立即执行?
【发布时间】:2016-04-28 03:32:21
【问题描述】:
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


【解决方案1】:

Javascript 代码只在一个线程上运行。 setTimeout 安排一个函数稍后运行。所以在 js 中,当所有当前正在运行的代码完成执行时,event 循环将寻找任何其他事件。 所以setTimeout( .. 0) 会让代码在当前循环之后运行。

console.log("I'm message from outside timeout"); 将首先被安排执行。一旦完成,setTimeout 就会被执行

所以底线setTimeout(myfunction ,0) 将在当前执行函数后 0 毫秒运行 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 以了解更多信息

【讨论】:

  • 您解释订单的方式令人困惑。 setTimeout 本身在console.log 之前执行,只有传递给它的函数被调度。
  • 关于“…最小超时 4 毫秒”,这不一定是真的。当前的WHATWG spec 表示“……然而,在五个这样的嵌套计时器之后,间隔被强制为至少四毫秒”。因此,最小延迟是实现设置的任何值。
  • 是的,“最少 4 毫秒”非常具有误导性。这是一个要验证的小提琴:jsfiddle.net/pgjbn8o5
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
相关资源
最近更新 更多