javascript - 允许在 nodejs 中每毫秒运行一次以上 setInterval

标签 javascript node.js loops setinterval

我有一个 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

setImmediate - Schedules the "immediate" execution of the callback after I/O events' callbacks. Returns an Immediate for use with clearImmediate().

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 and setTimeout 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.

process.nextTick

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/

相关文章:

javascript - 尝试通过传入函数来绑定(bind)回调会引发错误

javascript - innerHTML 关闭标签

node.js - Electron 应用程序利用GraphQL和MongoDB

angularjs - Angular 应用程序中实现的 Node 给出了语法错误和引用错误

node.js - node.js 中所需的结构化库的最佳实践

python - while 循环比 for 循环快 1000 倍以上?

python - PyQT 使用循环向选项卡添加数据/信息

c++ - 使用数组中的 count 参数索引我的 while 循环

javascript - 如何使ticks函数在d3.js中工作?

php - 如何通过强制另存为选项来保存网页的内容/文本