JavaScript Timers: setTimeout, setInterval, Cancelling, Delays, Throttling and Scheduling
Everything about timers: setTimeout and setInterval, cancelling with clear functions, why delays are minimums and setTimeout(fn, 0) isn't immediate, setInterval vs chained setTimeout, promise-based sleep, debounce and throttle, background tab throttling, and alternatives like requestAnimationFrame.
kvi5hnuCode Sprout team member7 min readOn this page
Timers schedule code to run later: hide a toast after three seconds, poll a server every minute, wait for the user to stop typing before searching. setTimeout and setInterval aren't part of the ECMAScript language (they come from the HTML standard), but every browser and Node.js provides them as globals. They're simple to call and surprisingly easy to misunderstand, which is why they come up in so many interviews.
setTimeout and clearTimeout
const id = setTimeout(() => {
showToast("Saved");
}, 3000); // run once, after at least 3000 ms
clearTimeout(id); // cancel it, if it hasn't run yet
- The first argument is a function. (Passing a string of code also works for legacy reasons, but it's evaluated like
eval, so never do it.) - The second is the delay in milliseconds; omitted, it's 0.
- Extra arguments are passed to the callback:
setTimeout(greet, 500, "Ana")callsgreet("Ana"). - It returns an ID: a positive number in browsers, a
Timeoutobject in Node. Pass it toclearTimeoutto cancel. Clearing an ID that already ran (orundefined) does nothing, so it's always safe.
setInterval and clearInterval
let ticks = 0;
const id = setInterval(() => {
ticks++;
console.log("tick", ticks);
if (ticks === 3) clearInterval(id);
}, 10);
tick 1
tick 2
tick 3
setInterval repeats until you clear it. Forgetting clearInterval is a classic leak: the callback (and everything it references) stays alive, and the work keeps running after the component or page section that needed it is gone.
Delays are minimums
A timer's delay is the earliest time the callback may run, not a promise that it will run then. Callbacks run on the main thread through the event loop, so they wait until the currently running code finishes:
const start = Date.now();
setTimeout(() => {
console.log("waited at least 100 ms:", Date.now() - start >= 100);
}, 0);
const end = Date.now() + 100;
while (Date.now() < end) {} // busy loop: the timer can't run until it ends
waited at least 100 ms: true
Other reasons timers run late:
- Nested timers are clamped. In browsers, after a timer chain is nested five levels deep, delays under 4 ms become 4 ms.
- Background tabs are throttled. Browsers run timers in hidden tabs at most about once per second, and Chrome throttles long-hidden pages further, to about once per minute for chains of timers. A countdown that assumes every
setIntervaltick is exactly one second will drift badly; compute remaining time fromDate.now()orperformance.now()instead. - Sleeping laptops and busy devices pause or delay everything.
- Huge delays overflow. Delays are stored as a 32-bit signed integer, so anything above 2,147,483,647 ms (about 24.8 days) wraps around and fires almost immediately. Node prints a
TimeoutOverflowWarning.
setTimeout(fn, 0) isn't immediate
A zero delay means "as soon as possible, after the current code and all pending microtasks":
console.log("start");
setTimeout(() => console.log("timeout 0"), 0);
Promise.resolve().then(() => console.log("promise then"));
queueMicrotask(() => console.log("queueMicrotask"));
console.log("end");
start
end
promise then
queueMicrotask
timeout 0
Timers are tasks (macrotasks); promise reactions are microtasks, and the microtask queue is always drained first. This ordering question is one of the most common JavaScript interview topics, and Part 13 (asynchronous JavaScript) explores the event loop behind it in depth.
setTimeout(fn, 0) is still useful to defer work: let the browser paint before a long computation, or break one big job into chunks so the page stays responsive.
setInterval vs chained setTimeout

setInterval schedules runs on a fixed rhythm, regardless of how long each run takes. If the work is slow, or async (like a fetch that takes longer than the interval), runs crowd together or overlap. Scheduling the next run at the end of the current one avoids that:
async function poll() {
try {
await refreshNotifications(); // might take 50 ms or 5 s
} finally {
pollTimer = setTimeout(poll, 30_000); // next poll 30 s after this one finished
}
}
let pollTimer = setTimeout(poll, 0);
// stop: clearTimeout(pollTimer)
Use setInterval for cheap, synchronous ticks (updating a clock display); use a setTimeout chain for anything slow, async or network-bound.
Promise-based delays
A sleep helper makes delays work with async/await:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function retry(task, attempts = 3) {
for (let i = 1; i <= attempts; i++) {
try {
return await task(i);
} catch (err) {
console.log(`attempt ${i} failed`);
if (i === attempts) throw err;
await sleep(10 * 2 ** i); // exponential backoff: 20 ms, 40 ms...
}
}
}
retry(async (i) => {
if (i < 3) throw new Error("flaky");
return "ok on attempt " + i;
}).then(console.log);
attempt 1 failed
attempt 2 failed
ok on attempt 3
Node also ships promise versions in node:timers/promises, which accept an AbortSignal for cancellation:
import { setTimeout as delay } from "node:timers/promises";
const result = await delay(500, "done"); // resolves to "done" after 500 ms
const controller = new AbortController();
const waiting = delay(10_000, null, { signal: controller.signal });
controller.abort(); // waiting rejects with an AbortError
For timeouts on async operations, AbortSignal.timeout(ms) creates a signal that aborts on its own: fetch(url, { signal: AbortSignal.timeout(5000) }) gives up after 5 seconds with a TimeoutError.
Debounce and throttle
Events like typing, scrolling and resizing can fire dozens of times per second. Two timer patterns tame them, and both are frequent interview questions.
Debounce waits until events stop for a given time, then runs once. Ideal for search-as-you-type and auto-save:
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
const search = debounce((query) => console.log("searching for", query), 50);
search("j");
search("ja");
search("jav");
search("java"); // only this one survives the burst
setTimeout(() => search("javascript"), 120); // a later, separate burst
searching for java
searching for javascript
Throttle runs at most once per interval, however often it's called. Ideal for scroll position tracking or rate-limiting button clicks:
function throttle(fn, interval) {
let last = -Infinity;
return function (...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
const onScroll = throttle((y) => console.log("handled scroll at", y), 1000);
for (let y = 0; y <= 400; y += 100) onScroll(y); // 5 rapid calls
handled scroll at 0
These are minimal versions. Production implementations (like lodash's) add options such as running on the leading and trailing edge and cancelling, and both functions keep this and arguments using apply (article 68).
this inside timer callbacks
A method passed directly to setTimeout loses its object, exactly like any other detached method:
const player = {
name: "Ana",
greet() { console.log("Hi,", this.name); },
};
setTimeout(player.greet, 100); // "Hi, undefined": this isn't player
setTimeout(() => player.greet(), 100); // "Hi, Ana"
setTimeout(player.greet.bind(player), 100); // "Hi, Ana"
Wrap it in an arrow function or use bind (article 68).
Other scheduling tools
| Tool | Runs | Use for |
|---|---|---|
queueMicrotask(fn) | after the current code, before any task | finishing work before the next event or render |
requestAnimationFrame(fn) | right before the browser's next repaint (usually 60+ times a second, paused in hidden tabs) | animations and visual updates |
requestIdleCallback(fn) | when the browser is idle | low-priority work like analytics |
scheduler.postTask(fn, { priority }) and scheduler.yield() | prioritized tasks; yielding back to the browser in long work | keeping long tasks responsive (check browser support) |
setImmediate(fn) (Node) | after I/O callbacks in the current loop iteration | deferring in Node |
process.nextTick(fn) (Node) | before promise microtasks | internal Node patterns; prefer queueMicrotask |
For animation, requestAnimationFrame is smoother and more efficient than setInterval(fn, 16), because it syncs to the display and stops when the tab is hidden.
Common questions
Why does setTimeout(fn, 1000) sometimes run after 1003 ms, or much later?
The delay is a minimum. The callback waits for the main thread to be free, and browsers throttle timers in background tabs. Measure elapsed time with Date.now() or performance.now() instead of counting ticks.
What does this print?
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
Answer
3 3 3. All callbacks share one function-scoped var i, which is 3 by the time they run. With let i, each iteration gets its own binding and it prints 0 1 2 (article 26).
How do I cancel all timers I started?
There's no built-in "clear all". Keep the IDs (or an AbortController whose abort handler clears them) and clear them when the feature shuts down, for example when a component unmounts.
Is await sleep(1000) blocking?
No. It pauses only the async function; the rest of the program, including event handlers and rendering, keeps running. A busy while loop is blocking, which is why you should never use one to pause.
Summary
setTimeoutruns a function once after a delay;setIntervalrepeats it;clearTimeout/clearIntervalcancel using the returned ID.- Delays are minimums: a busy thread, nesting clamps, background tab throttling and sleep make timers late. Delays above about 24.8 days overflow.
setTimeout(fn, 0)runs after the current code and all microtasks.- Prefer chained
setTimeoutoversetIntervalfor slow or async work, so runs never overlap. - Wrap
setTimeoutin a promise forsleep; Node'stimers/promisesandAbortSignal.timeoutadd cancellation and timeouts. - Debounce waits for a pause; throttle limits the rate. Use
requestAnimationFramefor animation.
Review quiz
Check your understanding of collections, typed arrays, regular expressions, dates, Temporal, Intl, the console, URLs and timers: Part 11 review quiz: The Standard Library.
Practice Questions
What does this print, and in what order?
setTimeout(() => console.log("A"), 0);
Promise.resolve().then(() => console.log("B"));
console.log("C");
Answer
C, B, A. Synchronous code first, then microtasks (the promise reaction), then the timer task.
Write a function timeout(promise, ms) that rejects if promise takes longer than ms.
Answer
const timeout = (promise, ms) => Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error("timed out")), ms))]);
For production, also clear the timer once the race settles, so it doesn't keep a Node process alive.
A countdown uses this code. Why is it wrong after the user switches tabs for a while, and how do you fix it?
setInterval(() => seconds--, 1000)
Answer
Background tabs throttle timers, so ticks are skipped or delayed and seconds falls behind real time. Store the end time (const endsAt = Date.now() + duration) and compute Math.ceil((endsAt - Date.now()) / 1000) on each tick.
Should a search box use debounce or throttle?
Answer
Debounce: you want one search after the user pauses typing, not a search every N milliseconds while they type.
Previous: URLs in JavaScript: the URL Class, URLSearchParams, Encoding and Safe URL Building
Next: JavaScript Iterators and Iterables: Symbol.iterator, the Iteration Protocol and Custom Iterables

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.