Async
setTimeout() and clearTimeout()
Run code later — once.
Why it exists
Plenty in interfaces happens "after a while": hide a notification after 3 seconds, start searching once the user stops typing, show a tip if they sit idle, abort a request that's taking too long. setTimeout is the basic building block for all of that, and for delays in async code.
Where it's used
- Toast notifications that disappear on their own.
debounce: postpone an action while the user is typing.- Request timeouts together with Promise.race.
- A delay in async code:
await new Promise((r) => setTimeout(r, 500)).
Syntax
const id = setTimeout(fn, delayMs);
clearTimeout(id);Examples
setTimeout(() => console.log("a second passed"), 1000);const log = [];
setTimeout(() => log.push("timer"), 0);
log.push("now");
await new Promise((r) => setTimeout(r, 10));
log; // → ["now", "timer"]let fired = false;
const id = setTimeout(() => (fired = true), 5);
clearTimeout(id);
await new Promise((r) => setTimeout(r, 20));
fired; // → falseclearTimeout cancels the callconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const start = Date.now();
await sleep(20);
Date.now() - start >= 15; // → trueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
setTimeout doesn't pause the program: it records the function in a queue for later and returns immediately. The code after it runs straight away.
Once the delay has passed and the current code has finished, the engine calls the function. So the delay is a minimum, not an exact time: if the main thread is busy, the call waits. Even setTimeout(fn, 0) runs only after the current synchronous code (and after the callbacks of already-settled promises).
The callback closes over the variables around it and sees their values at the time of the call.
setTimeout returns an id; clearTimeout(id) cancels the call. For repeated calls there's setInterval.
Traps
How it differs from…
- Promises:
Promise setTimeoutworks with callbacks; wrapped innew Promise, it becomes a delay you can await.- Closure
A timer callback is a closure: it sees the variables it was created among.
When to pick something else
Don't use setTimeout to "wait until it loads" — wait for the promise or the event itself. For animations, use CSS transitions or requestAnimationFrame, not chains of timers.