计时器是否在Node.js中的自己的线程上运行? [英] Do Timers run on their Own threads in Node.js?

查看:36
本文介绍了计时器是否在Node.js中的自己的线程上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有点困惑,我知道Javascript是一种单线程语言,但是在阅读有关事件循环的内容时.我知道,在setTimeout或setInterval的情况下,javascript会调用浏览器提供的Web API,这会产生一个新线程来对该线程执行计时器.但是在带有计时器的nod​​e.js环境中会如何执行/工作?

I am a bit confused here I know Javascript is a single-threaded language but while reading about the event loop. I got to know that in case of setTimeout or setInterval javascript calls web API provided by the browser which spawns a new thread to execute timer on that thread. but what happens in the case of node.js environment with timers how do they execute/work?

推荐答案

node.js中的计时器未使用任何线程.

No threads are used for timers in node.js.

node.js中的计时器与事件循环配合使用,并且不使用线程.node.js中的计时器存储在已排序的链表中,下一个计时器将在链表的开头触发.每次通过事件循环时,它都会检查链接列表中的第一个计时器是否已达到其时间.如果是这样,它将触发该计时器.如果没有,它将运行事件循环中正在等待的其他事件.

Timers in node.js work in conjunction with the event loop and don't use a thread. Timers in node.js are stored in a sorted linked list with the next timer to fire at the start of the linked list. Each time through the event loop, it checks to see if the first timer in the linked list has reached its time. If so, it fires that timer. If not, it runs any other events that are waiting in the event loop.

在事件循环的每个后续周期中,它都会继续检查下一个计时器是否计时.添加新计时器后,它将以正确的排序顺序插入到链表中.当它触发或被取消时,将从链接列表中删除它.

On each subsequent cycle through the event loop, it keeps checking to see if its time for the next timer or not. When a new timer is added, it is inserted into the linked list in its proper sorted order. When it fires or is cancelled, it is removed from the linked list.

如果事件循环无事可做,它可能会睡眠一小段时间,但不会在下一个定时器的定时器之后进入睡眠状态.

If the event loop has nothing to do, it may sleep for a brief period of time, but it won't sleep past the timer for the next timer.

有关该主题的其他参考文献:

Other references on the topic:

nodejs如何在内部管理计时器

在发生性能问题之前有多少个并发setTimeout?

NodeJ中有多个客户端请求

查看全文

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