What are the gotchas with setTimeout and setInterval?
Five of these problems explain almost every bug that people hit with timers.
The delay is a minimum and not a promise. The timer only runs after at least that much time has passed, and it runs later if the event loop was busy with other work. A delay of zero means "as soon as possible" and not "right now", and it will never run before the code that is already running has finished.
The callback receives no arguments. People often expect the delay to be handed to the callback, and it is not. If you need to carry some data into the callback, close over it with an arrow function, which is the normal way to do it.
Timers are cleared by their identifier and not by the function. The call gives you back a number, and that number is what you pass to clearTimeout or clearInterval. The setInterval function returns the same kind of identifier.
Intervals drift and can overlap. A repeating timer schedules the next call based on when it actually fired and not on when it was supposed to fire, so the timing slowly slips. And if the callback takes longer than the interval, the next call is queued as soon as the first one finishes, so the calls pile up instead of running at the same time.
Timers do not keep a browser page alive, but they do keep a Node process alive. In the browser the page disappears and the timer goes with it. In Node a timer that is still waiting keeps the event loop running, so a script that schedules a timer never exits until you clear it.
Two smaller details are worth knowing. In browsers, nested timers are limited to about four milliseconds after five levels of nesting, which is a deliberate way of slowing down runaway code. And the resolution of the timer itself is not exact, so timers are for scheduling approximate delays and never for measuring elapsed time accurately.