Not now — when the time comes: JavaScript timers setTimeout and setInterval
setTimeout handles once, setInterval handles repeatedly — but delay only promises "at least this long": 0 is not immediate, background tabs run even later, and anything over 2147483647 overflows. Following MDN's setTimeout and setInterval docs: async return, argument passing, the delay rules, the 4 ms nesting clamp, clearTimeout and clearInterval, recursive setTimeout, lost this, and string arguments — with a 100-mistake breakdown from a fictional cafe order page.

First, the boundaries of this guide. The site already has several JavaScript basics guides: the event loop guide explains how tasks queue up on a single thread, the Promise and async guide explains how to wait for an asynchronous result, the search-box debounce guide explains waiting until the user stops typing before searching once, and the cron jobs guide explains four ways to run cron on the server. This guide covers none of those. It covers just one thing: the two timers you use most in the browser, setTimeout and setInterval — one for "do this once, after a while", the other for "do this every so often". The "Qingshi Cafe" below is the same fictional practice project used in earlier guides: a small web tool that takes orders for a street-side cafe. Earlier guides covered how its order page makes decisions, loops, takes numbers, and now this one covers its two "after a while" jobs: flashing "Order received, please wait" a few seconds after a customer places an order, and refreshing the pickup-number board every half minute. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. All syntax and behavior of timers comes from MDN's official docs, "Window: setTimeout() method" and "Window: setInterval() method"; sources are listed in each article's meta information and evidence record. After reading this guide, you should be able to do four things: schedule something once with setTimeout, schedule something repeatedly with setInterval, know the rules that govern the delay number, and recognize the most common timer mistakes when you see them. The event loop guide left "how to schedule time" open; this guide fills that gap.
Step 1: The problem — the order page has two "after a while" jobs
The Qingshi Cafe order page has two "after a while" jobs. First, when a customer finishes an order and taps "Place order", the page should not just nail the words "Order received" to the screen at once; it should flash "Order received, please wait" three seconds later, so the customer can confirm the order really went through. Second, the pickup-number board must not draw once and freeze; it has to refresh every thirty seconds, swapping in new numbers as they appear. Both jobs share one trait: neither should happen "right now", and neither should "wait forever". Waiting with a loop would freeze the page — buttons stop responding, text stops updating, and the customer can only watch a spinner. Timers work the other way around: you tell the browser "call me after this long" or "call me every so often", then let go and carry on with other work; when the time comes, the browser calls you. setTimeout handles the first kind: it calls once. setInterval handles the second: it calls every so often. Remember this split for now: once means setTimeout, repeatedly means setInterval — both are "scheduling time", not "waiting for time".
Step 2: setTimeout — once, and it returns immediately
setTimeout is written as setTimeout(func, delay): the first argument is the function to run, the second is how many milliseconds to wait. MDN puts it plainly: setTimeout is an asynchronous function, meaning that it returns immediately after scheduling the callback function or code to run. It does not "wait", blocking execution of the lines of code after setTimeout() until the scheduled code has run. MDN's example makes the point best:
setTimeout(() => {
console.log("this is the first message");
}, 5000);
setTimeout(() => {
console.log("this is the second message");
}, 3000);
setTimeout(() => {
console.log("this is the third message");
}, 1000);
// Output:
// this is the third message
// this is the second message
// this is the first message
The three setTimeout calls are written in the order 5000, then 3000, then 1000 — but the output comes out reversed: the one that waits 1 second comes first, the 3-second one second, and the 5-second one last. MDN's explanation is that because the earlier calls have larger delays, the callbacks run in the reverse order to which they were scheduled. If setTimeout blocked until the callback finished, the output would appear in written order. One more return value to remember: setTimeout returns an ID, a positive integer in the browser — the timer's "ticket number", which you need later to cancel it. MDN's words: within the same global environment, the timeout ID is guaranteed not to be reused for any new timer as long as the original timer remains active; separate global environments, such as different windows or workers, maintain their own independent pools of timer IDs. The cafe example: after a customer places an order, setTimeout(showAccepted, 3000) runs showAccepted once three seconds later and flashes "Order received, please wait". Done.
Step 3: Passing arguments to the callback, no wrapper closure needed
setTimeout can also pass arguments straight to the callback: setTimeout(func, delay, param1, param2) — every argument after delay is passed through to func unchanged. MDN's example pairs two buttons with an output box:
let timeoutID;
function setOutput(outputContent) {
document.querySelector("#output").textContent = outputContent;
}
function delayedMessage() {
setOutput("");
timeoutID = setTimeout(setOutput, 2 * 1000, "That was really slow!");
}
function clearMessage() {
clearTimeout(timeoutID);
}
document.getElementById("show").addEventListener("click", delayedMessage);
document.getElementById("cancel").addEventListener("click", clearMessage);
Click "Show" and the output box shows "That was really slow!" two seconds later; click "Cancel" before the two seconds are up and the scheduled message is dropped — the text never appears. The call setTimeout(setOutput, 2 * 1000, "That was really slow!") is the argument-passing form: the third argument is handed straight to setOutput, with no arrow-function wrapper needed. setInterval passes arguments exactly the same way; MDN's example is setInterval(myCallback, 500, "Parameter 1", "Parameter 2"), and myCallback receives "Parameter 1" and "Parameter 2". My judgment: when there is one argument and it is already a plain string or number, pass it as the third argument — that is the cleanest form. When the argument has to be computed on the spot, or pulled out of an object at call time, wrap it in an arrow function instead; do not twist the code to save one line.
Step 4: The rules of the delay number — defaults to 0, negatives count as 0, strings get silently converted
The delay number has a few hard rules, spelled out in both MDN pages. First, if you omit delay it defaults to 0. Second, negative values behave the same as 0. Third — and the easiest one to trip over — if the value is not a number, the browser silently converts it to one, without throwing an error. MDN's example: passing the string "1000" still works, because it is coerced into the number 1000 and the code runs one second later; but passing "1 second" goes wrong — it is coerced into the number 0, so the callback runs immediately while the person who wrote the code believed they had scheduled one second. MDN's words: in many cases, the implicit type coercion can lead to unexpected and surprising results — so don't use strings for the delay value but instead always use numbers. Fourth, delay is converted to a signed 32-bit integer, which caps it at 2147483647 milliseconds, roughly 24.8 days, and anything larger overflows. MDN gives two examples: setTimeout(() => console.log("hi!"), 2 ** 32 - 5000) runs immediately, because 2 to the 32nd power minus 5000 overflows to a negative number; setTimeout(() => console.log("hi!"), 2 ** 32 + 5000) runs after approximately 5 seconds, because it overflows and leaves 5000 behind. MDN adds that in Node.js, any timeout larger than 2,147,483,647 ms results in immediate execution. The cafe example: the board refresh is written setInterval(refreshBoard, 30 * 1000) — the number 30000 is computed, clear and unambiguous. Writing setInterval(refreshBoard, "30 seconds") is asking for strange behavior: whether the string "30 seconds" converts to NaN or to 0 depends entirely on the browser's conversion rules. Do not gamble on it.
Step 5: The delay is "at least this long", not "exactly on time"
This is the most important sentence in the whole guide: delay means "wait at least this long", not "run exactly when this time arrives". MDN devotes a whole section to "Reasons for delays longer than specified". The most common case first: a delay of 0 does not mean "run now". MDN's example:
function foo() {
console.log("foo has been called");
}
setTimeout(foo, 0);
console.log("After setTimeout");
// Output:
// After setTimeout
// foo has been called
Even with a delay of zero, foo has to wait for the next round, until the code currently running has finished. MDN's words: even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. Currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected. The second case is a busy main thread: if the page, the operating system, or the browser is busy with other tasks, the callback gets pushed back. The third case is nested timeouts: the HTML standard says browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times. MDN's experiment nests setTimeout calls with a delay of 0 and logs each gap: the first four gaps are approximately 0 milliseconds, and after that they are approximately 4 milliseconds. The fourth case is inactive tabs: to save battery, browsers impose a minimum delay on background tabs. MDN's numbers: Firefox Desktop enforces a minimum timeout of 1 second for inactive tabs; Firefox for Android enforces 15 minutes and may unload the tab entirely; Chrome has three tiers — minimal throttling when the page is visible or recently made sound, timers checked once per second when the page has been invisible for less than 5 minutes, and intensive throttling, introduced in Chrome 88, when the page has been invisible for more than 5 minutes, silent for more than 30 seconds, and the nesting count is 5 or higher — timers in that state are checked once per minute. The fifth case is page load: Firefox will defer firing setTimeout() timers while the current tab is loading, until the main thread is deemed idle or the load event fires. The cafe example: if the computer showing the pickup board switches to another tab and nobody looks at it for half an hour, the 30-second refresh may in Chrome only be checked once a minute. Numbers arriving late is normal — it does not mean the code is broken.
Step 6: clearTimeout — a scheduled job can be cancelled
A scheduled job can be cancelled, and that is what the ID from step 2 is for. Save the return value of setTimeout, and call clearTimeout(thatID) before it fires — the callback will not run. The button example from step 3 is exactly this: click "Show" to schedule a message two seconds out, click "Cancel" to drop it. Two things to watch in practice. First, store the ID somewhere reachable — do not let it vanish inside a function. The step 3 example keeps it in an outer let timeoutID for exactly this reason. Second, clearTimeout and clearInterval are technically interchangeable, because setTimeout and setInterval share the same pool of IDs. MDN's words: be aware that setInterval() and setTimeout() share the same pool of IDs, and that clearInterval() and clearTimeout() can technically be used interchangeably. MDN follows that immediately with: for clarity, however, you should try to always match them to avoid confusion when maintaining your code. My judgment: cancel one-shot timers with clearTimeout and repeating timers with clearInterval, always matched — it saves the person reading the code three months later, who might be you, from guessing.
Step 7: setInterval — once every so often, and the first run waits too
setInterval is written exactly like setTimeout — setInterval(func, delay) — but the meaning changes: it runs func every delay milliseconds, and the first execution also waits one full delay; it does not run immediately. MDN's words: the first execution happens after delay milliseconds. The return value is again an ID, an interval ID, and passing it to clearInterval() stops the repeated execution. MDN's example is a box that flashes:
let intervalId;
function changeColor() {
// check if an interval has already been set up
intervalId ??= setInterval(flashText, 1000);
}
function flashText() {
const oElem = document.getElementById("my_box");
oElem.className = oElem.className === "go" ? "stop" : "go";
}
function stopTextColor() {
clearInterval(intervalId);
// release our intervalId from the variable
intervalId = null;
}
document.getElementById("start").addEventListener("click", changeColor);
document.getElementById("stop").addEventListener("click", stopTextColor);
Click "Start" and the text flashes once a second, switching between green and red; click "Stop" and it holds still. One detail is worth copying: intervalId ??= setInterval(flashText, 1000) means "only schedule if nothing is scheduled yet", so clicking "Start" ten times never creates ten timers flashing together. The cafe example: the board refresh is const boardTimer = setInterval(refreshBoard, 30 * 1000), and at closing time clearInterval(boardTimer) stops it. The same rule as setTimeout applies: once intervals are nested beyond five levels deep, the browser enforces a 4 ms minimum, and asking for less than 4 ms gets pinned to 4 ms.
Step 8: When the callback is slower than the interval, setInterval queues up — use recursive setTimeout
The easiest setInterval trap is a callback that takes longer to run than the interval itself. MDN's words: if there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using setTimeout(). MDN's example is polling a remote server every 5 seconds: network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time, so you may find yourself with queued up requests that won't necessarily return in order. The recommended pattern is recursive setTimeout:
(function loop() {
setTimeout(() => {
// Your logic here
loop();
}, delay);
})();
The idea is simple: schedule the next run only after the current logic has finished. MDN's words: while this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing. In other words, recursive setTimeout guarantees "no overlap", not "on time". My judgment: for jobs like the pickup-board refresh, where every run waits on the network, do not use setInterval — use recursive setTimeout: refresh once, wait for the answer, then schedule the next one. Numbers arriving a little late is fine; requests piling up out of order is the real trouble. The other way around, if the callback is always fast — switching a color, adding a number — setInterval is enough, and there is no need to add an extra layer of recursion.
Step 9: Passing a method straight to a timer loses this
Functions passed to setTimeout and setInterval run with normal function call semantics for determining this. MDN's words: for non-arrow functions, the this context is set to the globalThis (an alias for window in browsers) object. MDN's example is a counter:
class Counter {
constructor() {
this.data = new Map();
}
count(item) {
this.data.set(item, (this.data.get(item) || 0) + 1);
}
}
const counter = new Counter();
counter.count("foo"); // Successfully adds "foo" to the map
setTimeout(counter.count, 1000, "bar");
// TypeError: Cannot read properties of undefined (reading 'set')
Calling counter.count("foo") directly is fine, because this is counter. But passing counter.count straight to setTimeout means that when it runs a second later, this is no longer counter; this.data is undefined, and calling .set on it throws a TypeError. MDN gives three fixes. First, wrap the call in another anonymous function that calls the method with the correct context: setTimeout(() => counter.count("bar"), 1000), or written as setTimeout(function () { counter.count("bar"); }, 1000). Second, use an arrow function, which inherits the this context of its enclosing scope: setTimeout(() => { this.data.set(item, (this.data.get(item) || 0) + 1); }, 1000) — inside a method, this is the object the method belongs to. Third, use Function.prototype.bind() to create a new function with the correct this context: setTimeout(counter.count.bind(counter), 1000, "bar"). MDN gives the exact same example and the same three fixes in the setInterval page, because the this rule is identical on both sides. My judgment: beginners should remember the first fix — wrap it in an arrow function, it works every time. Once that feels natural, pick whichever of MDN's three fixes reads best. The cafe example: the board object has a board.refresh() method. Do not write setInterval(board.refresh, 30 * 1000); write setInterval(() => board.refresh(), 30 * 1000). Otherwise the refresh throws a TypeError when its turn comes, and the numbers freeze in place.
Step 10: Do not pass a string as the first argument — it is eval's relative
The first argument of setTimeout and setInterval can be a function, but it can also be a string — and a string gets compiled and executed as code. MDN's words: this can be used instead of passing a function, but is strongly discouraged for the same reasons that make using eval() a security risk. MDN's example:
const untrustedCode = "alert('Potentially evil code!');";
const id = setTimeout(untrustedCode, 1000);
If that string comes from a user, it becomes a cross-site scripting hole. MDN also writes that websites with a Content Security Policy specifying script-src or default-src will prevent such code from running by default. If it must be allowed, the mitigation is to always assign TrustedScript objects instead of strings, enforce trusted types with the require-trusted-types-for directive, and add the trusted-types-eval keyword to script-src — and MDN stresses that this acts in the same way as unsafe-eval, only allowing evaluation when trusted types are enabled. My judgment: there is no exception to this rule — always pass a function as the first argument. Writing setTimeout("refreshBoard()", 1000) means the same thing as writing eval, and a code review can reject it on sight. If you think you need to build code dynamically, first ask whether a function would do the job; nine times out of ten it will.
Step 11: Which one to use, and a checklist
Finally, the selection guide. For something that happens once, use setTimeout: flashing "Order received" three seconds after an order is placed is its job. For something that repeats and is fast every time, use setInterval: refreshing the pickup board every thirty seconds is its job. For something that has to wait on the network, or wait for the previous run to finish, use recursive setTimeout: refresh once, wait for the answer, then schedule the next one. For animation, use neither — use requestAnimationFrame, which MDN lists first in the "See also" of both pages, because it follows the screen's refresh cycle and timers do not. There are also two jobs timers cannot do. First, when the page or tab closes, the timers die with it; the server-side job of "run this every day at 3 a.m." belongs to cron, covered in the site's cron jobs guide — do not try to hold it up with setInterval. Second, debounce and throttle are both built on setTimeout: debounce means "wait until the user stops, then do it once", throttle means "do it once every so often". The exact recipes are in the site's search-box debounce guide; this guide covers only the timers themselves and does not re-teach them. Run through this checklist: did you pick setTimeout or setInterval correctly; did you save the ID, and do you call clearTimeout or clearInterval when the page no longer needs it; is delay a number, not a string, and not over 2147483647; did you pass a method straight in, and will this be lost; can the setInterval callback finish inside the interval, and if not, did you switch to recursive setTimeout; is the first argument a function, not a string?
The chart above shows the causes of 100 timer mistakes in one month on the fictional Qingshi Cafe order page: setInterval without clearInterval — still running after the page closed, or scheduled several times over after repeated clicks — 24; believing setTimeout(..., 0) runs immediately — 18; believing delay is exact time, then being surprised when a background tab or a busy main thread makes it late — 16; the callback taking longer than the interval, so requests piled up in a queue — 12; passing a method straight to setTimeout, losing this and getting a TypeError — 11; passing a string as the first argument — 10; passing a string or an oversized value as delay and expecting a long wait — 9. 24 + 18 + 16 + 12 + 11 + 10 + 9 = 100; the books balance. The top three mistakes add up to almost sixty percent, and they are all the same misunderstanding: treating a timer as punctual, immediate, and self-managing. A timer only promises "at least this long" — not on time, not immediately, and a scheduled timer keeps running until you cancel it. Every category in the chart maps to a step in this guide: the first to steps 7 and 6, the second to step 5, the third to step 5, the fourth to step 8, the fifth to step 9, the sixth to step 10, the seventh to step 4. The next time a timer misbehaves, check in this order: is the ID saved and cleared, is delay a number and not 0, and is the callback slower than the interval. Three steps will usually find it.
Back to the four things from the start: setTimeout schedules once, returns immediately, and its callback waits for the next round; setInterval runs every so often, its first run also waits one delay, and stopping it takes clearInterval; delay only promises "at least this long" — 0 is not immediate, background tabs run even later, and anything over 2147483647 overflows; pass arguments with the third parameter, wrap a method in an arrow function when this would be lost, and always pass a function as the first argument. The event loop guide explained "how tasks queue up"; this guide explained "how to schedule time". Together they give the full picture of time in the browser. After this guide, run the order page's two timers through the checklist: the order notice uses setTimeout once, the board refresh becomes recursive setTimeout, the IDs are saved, and everything is cleared at closing time. Then the numbers will stop going wrong.
Comments (0)
Sources
Related articles
The main thread has to draw the page and do the accounts, so it freezes the moment the work gets heavy. A worker is another thread in another global context, and the two sides talk only through messages. Following MDN's Using Web Workers and Worker docs: new Worker, postMessage and onmessage, structured-clone copying, what a worker can and cannot do, onerror and terminate(), SharedWorker, and transferable zero-copy — with a 100-mistake breakdown from a fictional cafe order page.
An array has to be computed all at once; a generator hands out one value at a time, only when asked. Following MDN's Iterators and generators, function*, and Generator docs: the next() protocol, function* and yield, for...of consumption, Symbol.iterator, yield* delegation, sending values in with next(x), throw() and return(), and when to use a generator at all — with a 100-mistake breakdown from a fictional cafe order page.
One missing layer in your data can blank the whole order page. Following MDN's Optional chaining, Nullish coalescing, and Logical nullish assignment docs: the three forms of ?., short-circuiting, optional calls and bracket access, ?? vs || on 0 and empty strings, the ?. + ?? combination, the ban on mixing ?? with || and &&, and ??= defaults — with a 100-mistake breakdown from a fictional cafe order page.