我有一个 Node 脚本,它应该利用单个 Node 进程可以获得的所有 CPU 资源。但是我发现 setInterval 太慢了。
果然我在文档中找到了这个:
When delay is larger than 2147483647 or less than 1, the delay will be set to 1.
来源:https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args
现在我想知道是否有办法进一步降低限制,或者是否有可以使用的替代功能。
我不能只使用普通循环,因为还有其他异步的东西需要同时运行。
编辑:
再说一遍:我不能只使用普通循环,因为还有其他异步的东西需要同时运行。
我不知道为什么这很难理解。
在正常循环运行时,您正在阻止其他所有内容的执行。将循环放在另一个异步执行的函数中并不重要。
这是什么意思?
让我们看一些例子:
setInterval(()=>{console.log('a')},1000) // asynchronous thing that needs to run in the background
while (true) {
// do whatever
}
这段代码会做什么?它会阻止一切。 console.log('a')
不会连续执行。
setInterval(()=>{console.log('a')},1000) // asynchronous thing that needs to run in the background
setTimeout(()=>{
while (true) {
// do whatever
}
}, 1)
这也将在 while 循环开始时立即阻止间隔的执行。
最佳答案
我相信问题属于 node 而不是浏览器。您可以使用以下一些选项(递归/循环)来减少延迟时间。
setImmediate
- Schedules the "immediate" execution of the callback after I/O events' callbacks. Returns an Immediate for use withclearImmediate
().When multiple calls to setImmediate() are made, the callback functions are queued for execution in the order in which they are created. The entire callback queue is processed every event loop iteration. If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration.
来自 node
导游:
setImmediate
andsetTimeout
are similar, but behave in different ways depending on when they are called.
setImmediate()
is designed to execute a script once the current poll phase completes.setTimeout(
) schedules a script to be run after a minimum threshold in ms has elapsed.
The
process.nextTick()
method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.
来自 node
指导
We recommend developers use setImmediate() in all cases because it's easier to reason about (and it leads to code that's compatible with a wider variety of environments, like browser JS.)
关于javascript - 允许在 nodejs 中每毫秒运行一次以上 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48380108/