Very fast endless loop without I / O lock

Is there a faster alternative window.requestAnimationFrame()for infinite loops that don't block I / O?

What I am doing in the loop is not related to animation, so I don’t care when the next frame is ready, and I read that it is window.requestAnimationFrame()limited by the refresh rate of the monitor or at least waits until the frame can be taken.

I also tried the following:

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

(4 is because this is the minimum interval in setTimeout, and lower defaults will be 4.) However, I need a better resolution than this.

Is there anything with even better performance?

I basically need a non-blocking version while(true).

+4
2

, , setTimeout:

  • process.nextTick ( NodeJS):

    process.nextTick() " ". , , , .

    setTimeout(fn, 0). . , - ( ) .

, , setTimeout .

:

, , , JavaScript ( ); , , , , NodeJS .

: , ( setTimeout ), "", ( "" ). , , β€” ​​ .

nextTick . , , , .

, setInterval :

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>
Hide result

Hog, , , . - 300 000 , . , ( , , , ).

, , .


. setInterval , setInterval, , NodeJS, NodeJS setInterval .

+4

Source: https://habr.com/ru/post/1671213/


All Articles