At a fundamental level it’s important to understand how JavaScript timers work. Oftentimes they behave unintuitively because of the single thread which they are in. Let’s start by examining the three functions that we have access to with which to construct and manipulate timers.
var id = setTimeout(fn, delay);
– Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.var id = setInterval(fn, delay);
– Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.clearInterval(id);
– Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.
In order to understand how the timers work internally there’s one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread, asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution. This is best demonstrated with a diagram, like in the following: