[Javascript] Scheduling: setTimeout and setInterval

Suyeon·2020년 9월 7일
0

Javascript

목록 보기
16/31

Nested setTimeout

  • The nested setTimeout is a more flexible method than setInterval. This way the next call may be scheduled differently, depending on the results of the current one.
  • Nested setTimeout allows to set the delay between the executions more precisely than setInterval.
/** instead of:
let timerId = setInterval(() => alert('tick'), 2000);
*/

let timerId = setTimeout(function tick() {
  alert('tick');
  timerId = setTimeout(tick, 2000); // (*)
}, 2000);

For instance, we need to write a service that sends a request to the server every 5 seconds asking for data, but in case the server is overloaded, it should increase the interval to 10, 20, 40 seconds…

let delay = 5000;

let timerId = setTimeout(function request() {
  ...send request...

  if (request failed due to server overload) {
    // increase the interval to the next run
    delay *= 2;
  }

  timerId = setTimeout(request, delay);

}, delay);

Compare between setTimeout and setInterval

// setInterval
let i = 1;
setInterval(function() {
  func(i++);
}, 100);

// setTimeout
let i = 1;
setTimeout(function run() {
  func(i++);
  setTimeout(run, 100);
}, 100);

setInterval

  • The real delay between func calls for setInterval is less than in the code.

setTimeout

  • The nested setTimeout guarantees the fixed delay (here 100ms).
  • Because new call is planned at the end of the previous one.
profile
Hello World.

0개의 댓글