What are setTimeout and setInterval?
The setTimeout and setInterval functions are fundamental tools in JavaScript for managing time and scheduling code execution asynchronously via the event loop mechanism. The setTimeout(fn, ms) method is used to execute a passed function fn once after a specified number of milliseconds ms has elapsed. This is useful for creating delayed actions, such as hiding a popup notification after three seconds or implementing debounce when typing text into a search field.
In turn, the setInterval(fn, ms) method is designed for cyclically repeating a specified function at regular time intervals. It continues to run until execution is forcibly stopped. Both methods return a unique numeric timer identifier (ID) used to cancel them. To cancel a scheduled single call, the clearTimeout(timerId) function is used, and to stop a repeating interval, clearInterval(timerId) is used, which is a mandatory requirement to prevent memory leaks, for example, when unmounting components in frameworks.
It is important to understand how these timers work in the browser. The specified delay in milliseconds is not a guaranteed time for exact execution, but rather represents only the minimum allowable pause. Due to the single-threaded nature of JavaScript and the way the Event Loop works, if the main thread is busy with heavy computations, the timer will wait in line. In addition, in modern browsers, for nested timers or inactive tabs, there is a hardware limitation on the minimum delay, which is usually around 4 milliseconds.