Timers

Updated · 7 min read
mediumES2026javascripttimerssettimeoutsetinterval

Timers schedule a function to run later: once after a delay with setTimeout, or repeatedly with setInterval. They power reminders, auto-saving, polling a server, debouncing a search box and countdown displays. Timers are provided by the runtime, not the JavaScript language, but both browsers and Node.js have them with the same names. The key fact to understand: a timer's delay is a minimum, because the callback can only run when the main thread is free.

In One Minute

  • setTimeout(fn, ms, ...args) runs fn once after at least ms milliseconds; it returns an ID.
  • setInterval(fn, ms) runs fn every ms milliseconds until stopped.
  • clearTimeout(id) and clearInterval(id) cancel them.
  • Delays are minimums: callbacks wait for the current code to finish, and browsers slow timers in background tabs.
  • For animation, use requestAnimationFrame; for repeated async work, prefer a recursive setTimeout.

setTimeout

Syntax

syntax.js
const id = setTimeout(callback, delayInMs, arg1, arg2);
clearTimeout(id);

Example

timeout.js▶ Try it
console.log("Payment saved");
 
setTimeout(() => {
  console.log("Receipt emailed (after 50 ms)");
}, 50);
 
setTimeout((name, amount) => {
  console.log(`Reminder: ${name} owes $${amount}`);
}, 10, "Srihitha", 85);
 
console.log("Back to the user right away");
Output
Payment saved
Back to the user right away
Reminder: Srihitha owes $85
Receipt emailed (after 50 ms)

Explanation: setTimeout doesn't pause the program. It registers the function and returns immediately, so "Back to the user right away" prints second. The callbacks run later, in order of when they're due: the 10 ms timer before the 50 ms one. Extra arguments after the delay are passed to the callback.

Canceling a Timeout

setTimeout returns an ID (a number in browsers, an object in Node.js). Pass it to clearTimeout to cancel before it runs:

clear-timeout.js▶ Try it
const undo = setTimeout(() => console.log("Payment deleted"), 30);
console.log("Delete scheduled. Undo?");
 
setTimeout(() => {
  clearTimeout(undo);
  console.log("Undone: nothing was deleted");
}, 10);
Output
Delete scheduled. Undo?
Undone: nothing was deleted

This is the "Undo" pattern: delay a destructive action briefly and cancel it if the user changes their mind. Calling clearTimeout with an ID that already ran, or with undefined, does nothing and doesn't throw.

setInterval

setInterval repeats a function at a fixed interval until you clear it:

interval.js▶ Try it
let secondsLeft = 3;
const id = setInterval(() => {
  console.log(`Session ends in ${secondsLeft}...`);
  secondsLeft--;
  if (secondsLeft === 0) {
    clearInterval(id);
    console.log("Session ended");
  }
}, 20);
Output
Session ends in 3...
Session ends in 2...
Session ends in 1...
Session ended

Delays Are Minimums

A timer callback can only run when the call stack is empty: JavaScript finishes whatever it is doing first. A long task delays every timer:

minimum.js▶ Try it
const start = Date.now();
setTimeout(() => {
  const waited = Date.now() - start;
  console.log(`Asked for 10 ms, waited at least 100 ms: ${waited >= 100}`);
}, 10);
 
while (Date.now() - start < 100) {
  // a slow calculation that blocks the main thread for 100 ms
}
console.log("Slow work done");
Output
Slow work done
Asked for 10 ms, waited at least 100 ms: true

Explanation: the timer was due after 10 ms, but the loop held the main thread for 100 ms, so the callback had to wait. The exact time differs per run, so the example prints only whether it waited at least 100 ms.

Other reasons a timer runs late:

CauseEffect
Busy main threadWaits until current code finishes
Nested timersAfter 5 levels of nesting, browsers enforce at least 4 ms
Background tabBrowsers throttle timers to about once per second, or less
Sleeping deviceTimers don't run at all while asleep
setTimeout(fn, 0)Still waits for the current code and other queued tasks

So never use timers for precise timekeeping. A countdown should compute the remaining time from the clock (Date.now() or performance.now()) on each tick, not count ticks.

Recursive setTimeout vs setInterval

setInterval fires on a fixed schedule even if the previous callback hasn't finished its work (for example, a slow network request). A recursive setTimeout schedules the next run only after the current one completes, so runs never overlap and the gap is always respected:

recursive.js▶ Try it
let checks = 0;
 
function pollForPayments() {
  checks++;
  console.log(`Checking for new payments (#${checks})`);
  if (checks < 3) {
    setTimeout(pollForPayments, 20);
  } else {
    console.log("Stopped polling");
  }
}
 
pollForPayments();
Output
Checking for new payments (#1)
Checking for new payments (#2)
Checking for new payments (#3)
Stopped polling

This shape is also easy to extend with backoff (waiting longer after each failure) and to stop cleanly. Use it for polling servers; the async chapter adds await to it.

Timers and this

Passing a method directly to a timer loses its this, because the timer calls it as a plain function:

timer-this.js▶ Try it
const reminder = {
  studentName: "Advitha",
  send() {
    console.log(`Reminder sent to ${this?.studentName}`);
  },
};
 
setTimeout(reminder.send, 0);
setTimeout(() => reminder.send(), 0);
Output
Reminder sent to undefined
Reminder sent to Advitha

Wrap the call in an arrow function, or use reminder.send.bind(reminder).

Promise-Based Timers

A delay that can be awaited is a one-line promise wrapper (promises and await are explained in the async chapter). Node.js also provides one built in, in node:timers/promises:

sleep.js▶ Try it
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
 
console.log("Saving...");
await sleep(20);
console.log("Saved");
Output
Saving...
Saved

In Practice

The Fee Tracker auto-saves a note a short time after the person stops typing, instead of on every keystroke. This pattern is called debouncing: each keystroke cancels the pending save and schedules a new one:

autosave.html
<textarea id="note"></textarea>
<p id="status"></p>
<script>
  const note = document.querySelector("#note");
  const status = document.querySelector("#status");
  let timer;

  note.addEventListener("input", () => {
    status.textContent = "Typing...";
    clearTimeout(timer);
    timer = setTimeout(() => {
      status.textContent = `Saved: "${note.value}"`;
      console.log(status.textContent);
    }, 250);
  });
</script>
Output
Saved: "Paid by check"

The checker changed the note twice within 250 ms; only the final value was saved, once. The performance lesson turns this into a reusable debounce function.

Common Mistakes

Forgetting to clear intervals. They run forever and leak memory. Store the ID and call clearInterval.

Expecting exact timing. Delays are minimums. Compute elapsed time from the clock.

Passing a string to setTimeout. setTimeout("save()", 100) evaluates code from a string, like eval; it's blocked by Content Security Policy. Pass a function.

Calling the function instead of passing it. setTimeout(save(), 100) runs save now.

Practice

Challenge: Write countdown(n, ms) that logs n, n-1... down to 1 with ms between each, then logs "Go!", using recursive setTimeout.

Show solution
countdown.js▶ Try it
function countdown(n, ms) {
  if (n === 0) {
    console.log("Go!");
    return;
  }
  console.log(n);
  setTimeout(() => countdown(n - 1, ms), ms);
}
 
countdown(3, 10);
Output
3
2
1
Go!

Quick check: Timers

3 questions
1What does setTimeout(fn, 100) guarantee?
2How do you stop a setInterval?
3Why prefer recursive setTimeout for polling a server?

Key Takeaways

TaskCode
Run once laterconst id = setTimeout(fn, ms)
CancelclearTimeout(id)
Repeatconst id = setInterval(fn, ms)
Stop repeatingclearInterval(id)
Await a delayawait new Promise((r) => setTimeout(r, ms))

Was this tutorial helpful?

Lesson 79 of 139