非常快的无限循环没有阻止I / O

有没有更快的替代window.requestAnimationFrame()无限循环不阻止I / O?

我在循环中所做的与animation无关,因此我不在乎下一帧何时准备就绪,并且我已经读取了window.requestAnimationFrame()以监视器的刷新率为上限,或者至less等到框架可以绘制。

我也尝试了以下内容:

 function myLoop() { // stuff in loop setTimeout(myLoop, 4); } 

(这是因为这是setTimeout的最小间隔,较小的值仍将默认为4.)但是,我需要比这更好的分辨率。

那里有更好的performance吗?

我基本上需要while(true)的非阻塞版本。

有两件事会比setTimeout更快运行:

  • process.nextTickcallback(NodeJS专用):

    process.nextTick()方法将callback添加到“下一个打勾队列”中。 一旦事件循环的当前轮到运行完成,当前在下一个滴答队列中的所有callback将被调用。

    这不是setTimeout(fn, 0)的简单别名。 这是更有效率。 它在任何其他I / O事件(包括定时器)在事件循环的随后滴答中触发之前运行。

  • 承诺和解通知

所以这些可能是你的工具带的一个工具,用setTimeout混合一个或两个来达到你想要的平衡。

细节:

正如你可能知道的,一个给定的JavaScript线程在任务队列的基础上运行(规范称它为一个工作队列)。 正如您可能知道的那样,浏览器中有一个主要的默认UI线程,NodeJS运行一个线程。

但实际上,在现代实现中至less有两个任务队列:我们都认为的主要任务队列( setTimeout和事件处理程序放置任务的地方),以及处理期间放置某些asynchronous操作的“微任务”队列主要任务(或“macrotask”)。 这些微任务在macros任务完成之后立即被处理, 主队列中的下一个macros任务之前 – 即使下一个macros任务在微任务之前排队。

nextTickcallback和承诺结算通知都是微任务。 所以调度要么调度asynchronouscallback,而要在下一个主要任务之前发生。

我们可以在带有setInterval和承诺parsing链的浏览器中看到:

 let counter = 0; // setInterval schedules macrotasks let timer = setInterval(() => { $("#ticker").text(++counter); }, 100); // Interrupt it $("#hog").on("click", function() { let x = 300000; // Queue a single microtask at the start Promise.resolve().then(() => console.log(Date.now(), "Begin")); // `next` schedules a 300k microtasks (promise settlement // notifications), which jump ahead of the next task in the main // task queue; then we add one at the end to say we're done next().then(() => console.log(Date.now(), "End")); function next() { if (--x > 0) { if (x === 150000) { // In the middle; queue one in the middle Promise.resolve().then(function() { console.log(Date.now(), "Middle"); }); } return Promise.resolve().then(next); } else { return 0; } } }); $("#stop").on("click", function() { clearInterval(timer); }); 
 <div id="ticker">&nbsp;</div> <div><input id="stop" type="button" value="Stop"></div> <div><input id="hog" type="button" value="Hog"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

有一些库可以像cron任务一样工作,例如https://www.npmjs.com/package/node-cron

我认为使用cron应该更容易,更灵活。