2

I am struggling to think of a use case in web-application development that needs to use setInterval.

The "danger" with setInterval being that it just queues up callbacks should one not complete within the allocated interval.

Furthermore, the behaviour of setInterval can be simulated with setTimeout or requestAnimationFrame without this "danger".

Given this, can someone provide me with a use-case where setInterval is the superior/more appropriate option?

Edit:

Thought I'd jot down my findings.

setInterval is an easy way to have something run at even-ish intervals. The intervals will mainly be quite accurate, but if the event loop is blocked, then they might be completely inaccurate.

var x = 0;
setInterval(function() { 
   waitBlocking(5000);
   document.write(x++);
},100);

function waitBlocking(ms) {
    var start = Date.now();
    while((Date.now() - start) < ms) {}
}

As far as I can tell, setInterval is useful not if you want evenly spread interval callback invocations (see above), but if you want a convenient way of having a specific number of callback invocations in a period, spread across the timeframe as close as possible to when they should have run. Which seems like a rather narrow use case.

I'm sure I am missing something.

Edit 2:

This is basically the best approximation of a clock JS can achieve, so I guess setInterval is the "clock timer". Presumably this was useful in applications that needed simple clocks.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 2
    I would disagree that that functionality is a "danger" of `setInterval`; it is a specific feature, and is useful in situations where you want your callbacks to execute on a specific schedule that is independent of how long the callback takes to execute. – Hamms Jun 20 '16 at 20:41
  • Being single threaded, it is not independent, but I take your point. – Ben Aston Jun 20 '16 at 21:14
  • 1
    "being that it just queues up callbacks should one not complete within the allocated interval." --- that's not entirely true. Only up to one extra call is queued. The benefit of `setInterval` is that you don't need to manage the next call manually (otherwise you spoil your domain-specific code with setting up `setTimeout`). Not to say that not always it is an anonymous function that you can easily hack but a reference to a function from a variable. – zerkms Jun 20 '16 at 22:18
  • Please can you supply the reference for "upto one extra call is queued". This is the observed behavior, but I couldn't tease it out of https://www.w3.org/TR/2011/WD-html5-20110525/timers.html#dom-windowtimers-setinterval – Ben Aston Jun 20 '16 at 22:34
  • @BenAston "Each object that implements the WindowTimers interface has a list of active timeouts and a list of active intervals. Each entry in these lists is identified by a number, which must be unique within its list for the lifetime of the object that implements the WindowTimers interface." – zerkms Jun 20 '16 at 23:48
  • `setInterval` returns a unique ID to use with `clearInterval` later. `requestAnimationFrame` and `setTimeout` also return unique IDs, but a different one for each call - something you need to handle if you call them recursively. – le_m Jun 21 '16 at 00:01

1 Answers1

1

The use-case where setTnterval is appropriate is when you want to execute a function at an exact time. setInterval and setTimeout has subtitle differences. setInterval execute it function after delay starting from the time when the previose setInterval fired. setInterval is also not reclusive so there is no fear of closures and memory leaks. More details can however be found here

Below is the code for a typical setInterval function

var intervalID = window.setInterval(myCallback, 500);

function myCallback() {
  // Your code here
}

Where as to achieve the same function using setTimeout you will have to create a recursion which can create closures and then the problem of memory leaks comes in as demonstrated below.

function startTimer() {   
    var count = [1,2,3,4,5,6,7,8,9,0]
    setTimeout(function() {
        //do some stuff
        count.push(100);//you have just create a closure 
        //and all the problems that is associated with it
        startTimer();//this is where the recursion happens 
    }, 1000);
}
Community
  • 1
  • 1
spirit
  • 283
  • 2
  • 16
  • I was thinking about the same answer, but then I looked Ben's profile, he has 11k reputation, he is a Javascript consultant, he wrote many javascript articles on Medium and realized that probably he is looking for a more pragmatic answer :) Wait! What? I'm not a stalker... – Devid Farinelli Jun 20 '16 at 20:49
  • 1
    Ok thanks for the tip let me include some codes to better illustrate my answer – spirit Jun 20 '16 at 21:11