JavaScriptEasy
setTimeout vs setInterval?
setTimeout(fn, delay) runs a function once after at least delay milliseconds; setInterval(fn, delay) runs it repeatedly every delay milliseconds until you stop it with clearInterval.
Both
- Return an id you pass to
clearTimeout/clearInterval. - Accept extra arguments that are passed to the callback.
- Are minimum delays, not guarantees. The callback runs only when the call stack is empty and the event loop reaches it, so busy code delays it.
- Are throttled in background tabs (often to once per second or less) and nested timers are clamped to at least 4 ms after a few levels.
Problems with setInterval
- It schedules the next run regardless of whether the previous one finished. If the callback is slow or async (a network poll), runs can overlap or pile up.
- It keeps going forever if you forget to clear it, which is a common memory leak in components.
Recursive setTimeout
Scheduling the next run at the end of the current one guarantees a gap between runs and makes it easy to change the delay (backoff) or stop based on a condition. This is the preferred pattern for polling.
For animations
Use requestAnimationFrame, which syncs with the display refresh rate and pauses in hidden tabs.
Cleanup
In React, clear timers in the effect cleanup function so they do not fire after the component unmounts.
Code example
js
1// setTimeout: once2const id = setTimeout((name) => console.log(`Hello ${name} (once)`), 20, "Ada");34// setInterval: repeatedly, until cleared5let ticks = 0;6const intervalId = setInterval(() => {7 ticks++;8 console.log("tick", ticks);9 if (ticks === 3) clearInterval(intervalId); // always stop it10}, 10);1112// Recursive setTimeout: the next run starts only after the previous finished13async function poll(task, { delay = 20, maxRuns = 3 } = {}) {14 let runs = 0;15 return new Promise((resolve) => {16 const run = async () => {17 runs++;18 const result = await task(runs);19 if (result === "done" || runs >= maxRuns) return resolve(runs);20 setTimeout(run, delay * runs); // easy to add backoff21 };22 run();23 });24}2526const runs = await poll(async (n) => {27 console.log("poll attempt", n);28 return n === 2 ? "done" : "pending";29});30console.log("finished after", runs, "polls"); // finished after 2 polls
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.