Note: The following is a translation of the John Resig “How JavaScript Timers Work” note, in which the author of jQuery clearly and in detail describes the subtleties of the work of various methods of deferred execution of functions.My comments on customer performance are in italics.
At its most fundamental level, it is extremely important to understand how timers work in JavaScript. Very often, the work of timers seems counterintuitive due to the fact that they are all running within the same thread. But let's start by describing the three main functions that we use to create and manage our timers.
var id = setTimeout(fn, delay); - creates a single timer, the operation of which results in a call to a specific function after the specified delay. This method returns a unique ID with which you can later cancel the timer.
var id = setInterval(fn, delay); - is similar to the previous setTimeout , but makes calls to a given function constantly (each time with a specified delay) until it is canceled.
clearInterval(id); , clearTimeout(id); - accept the ID of the timer as a parameter (returned by the two previous methods) and prevent further timer calls.
')
In order to understand the internal aspects of the work of timers, it is worth considering one important detail that should be covered: the delay in the execution of the timer is not guaranteed. Since all JavaScript is executed in a browser in one thread, asynchronous events (for example, mouse clicks or timers) are triggered only by the appearance of a “window” in this main thread ( event handlers and called functions are, in fact, “embedded” in the main execution thread, more on the organization of heavy computing ). This can best be demonstrated using the following diagram: