本文介绍了使用阻塞代码的setTimeout行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试代码(小提琴):

This is my test code (fiddle here):

console.log('Before wait');
setTimeout(function () { console.log('Yo!'); }, 1000);
var start = Date.now();
while (Date.now() < start + 3000) {}
console.log('After wait');

这是Chrome中事件的时间轴:

This is the timeline of events in Chrome:


  • 时间0秒:打印等待前

  • 时间3秒:打印等待后,然后立即打开哟!

此行为是否符合规范?为什么不是

Is this behaviour according to spec? Why is it not


  • 时间0秒:打印等待前

  • 时间3秒:打印等待后

  • 时间4 seoncds:打印哟!

推荐答案

setTimeout 的延迟是相对于确切的时间点它被称为。当你还在忙着等待时,它会过期。所以它将在下一个控制回到事件循环的瞬间执行。

The delay of setTimeout is relative to the exact point in time when it is called. It expires while you are still busy waiting. So it will be performed at the next instant where the control goes back into the event loop.

编辑:

规范在这一点上有点模糊,但我想这是有意和唯一直接的解释:

The spec is a bit vague in this point, but I guess it's the intended and only straightforward interpretation:

此方法在经过指定的毫秒数后调用该函数,直到通过调用clearTimeout取消。
方法返回一个timerID,可以在后续调用
clearTimeout时使用它取消间隔。

This method calls the function once after a specified number of milliseconds elapses, until canceled by a call to clearTimeout. The methods returns a timerID which may be used in a subsequent call to clearTimeout to cancel the interval.

这篇关于使用阻塞代码的setTimeout行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 03:02