The difference between window.setTimeout() and window.setInterval()

From what I’ve seen, the problem most people have with the difference between these two JavaScript functions isn’t knowing what they do, but it’s knowing that they both exist. I’ve seen lots of people constantly call setTimeout() calling the same function over and over where the last line of the function calls setTimeout(), but setInterval() is probably what they really wanted, they just didn’t know it existed. But I’ve also seen lots of code that calls setInterval() to execute a function after a specific delay, and the first thing that function does is call clearInterval(), so they obviously really wanted the functionality of setTimeout(). I guess it’s mostly a result of people finding one thing that gets the job done, and never looking for anything else.

The difference between the two functions is fairly trivial. setTimeout() executes the function only once, unless you call it again; and setInterval() continuously calls the function until clearInterval() is called. The only disadvantage to using setTimeout() when you really wanted the functionality of setInterval is that the time between each call will vary depending on how long it takes your code to execute (and sometimes you actually want that feature). There is some danger in using setInterval() and hoping your code is fast enough to call clearInterval() before the interval time passes. In such a case, the next call is queued and will execute your function any number of times depending on how many times the interval time passed while your code was running.

Leave a Reply