setTimeout如何在Node.JS中工作? [英] How does setTimeout work in Node.JS?

查看:124
本文介绍了setTimeout如何在Node.JS中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一旦它被执行了它就在队列中,但在队列中是否有任何保证它会在X毫秒后完全调用?或者队列中其他较重的任务会延迟吗?

I guess that once it's executed it's on the queue, but in the queue is there any assurance it will invoke exactly after X milliseconds? Or will other heavy tasks higher on the queue delay it?

推荐答案

setTimeout的语义与Web浏览器的语义大致相同:超时arg是执行前要等待的最小 ms,而不是保证。此外,传递0,非数字或负数将使其等待最小数量的ms。在Node中,这是1ms,但在浏览器中它可以长达50ms。

The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.

原因是JavaScript没有抢占JavaScript。考虑这个例子:

The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:

setTimeout(function () {
  console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')

这里的流程是:


  1. 安排超时100ms。

  2. busywait for 5000ms。

  3. 返回事件循环。检查挂起的计时器并执行。

如果不是这种情况,那么你可以让一点JavaScript中断另一个。我们必须设置互斥和信号等,以防止这样的代码极难推理:

If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:

var a = 100;
setTimeout(function () {
  a = 0;
}, 0);
var b = a; // 100 or 0?

Node的JavaScript执行的单线程性使得它比大多数其他类型的并发更简单易用。当然,权衡的是,程序中一个表现不好的部分可能会以无限循环阻止整个事件。

The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.

这是一个更好的恶魔要比先发制人的复杂性还要战斗?这取决于。

Is this a better demon to battle than the complexity of preemption? That depends.

这篇关于setTimeout如何在Node.JS中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆