0

I have these snippets of code that do the same thing but use different approaches - setInterval and continuous setTimeout calls:

function log() {
  console.log('fn')
}

//option 1
var forTimes = 10;
var doneTimes = 0;

var interval = setInterval(function(){
  if (doneTimes < forTimes) {
    log();
    doneTimes++;
  } else {
    clearInterval(interval);
  }
}, 100);

//option 2
function timeoutFn() {
  if (doneTimes < forTimes) {
    log();
    doneTimes++;
    setTimeout(timeoutFn, 100);
  }
}
setTimeout(timeoutFn, 100);

Because of the nature of single-threaded javascript neither setTimeout nor setInterval guarantees functional call witing 100 ms since thread may be busy running an event handler or doing reflow/repaint. I'm wondering if any of them has higher likelyhood of executing handler within the specified time? If so, why? Does setInterval act like setTimeout in that it waits for the specified interval to pass and only after that adds handler to the queue?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

2

setInterval is kind of seen as bad practice these days because you have a function being executed at intervals regardless of whether or not the previous call to the function has completed.

With regards to exact time neither is better or worse really.

The best method would be to do a recursive setTimeout Pattern:

var count = 0;
(function loopsiloop(){
   setTimeout(function(){
      if(count < 10) {
         loopsiloop();
      }

      ++count;
   }, 100);
})();
Michael Tempest
  • 814
  • 7
  • 12