Reading history

JavaScript Timers: setTimeout, setInterval and sleep()

5 min read 1 views

Use setTimeout and setInterval, cancel timers, see why a 0ms delay still waits, and build sleep(), timeouts with Promise.race and retry with backoff.

Many programs need to do something later: hide a message after three seconds, refresh a score every minute, or give up on a slow request. JavaScript does this with timers. setTimeout runs a function once after a delay, and setInterval runs it again and again. Combined with promises, timers also give you a sleep() function, timeouts for slow work, and automatic retries. This lesson covers all of these, with real timings so you can see exactly when each line runs.

In this lesson you will learn

  • setTimeout and clearTimeout
  • setInterval and clearInterval
  • Why a delay of 0 still waits
  • A promise-based sleep() for async code
  • Timeouts with Promise.race and retrying failed work

You should know promises and async/await. The event loop lesson explains what happens behind the scenes.

setTimeout and setInterval

"use strict";
const start = Date.now();
const t = () => `${Math.round((Date.now() - start) / 100) * 100}ms`;   // rounded elapsed time

// setTimeout runs a function once, after a delay in milliseconds
setTimeout(() => console.log(t(), "timeout 300 done"), 300);
setTimeout(() => console.log(t(), "timeout 100 done"), 100);

// clearTimeout cancels a timer before it runs
const cancelled = setTimeout(() => console.log("this never prints"), 200);
clearTimeout(cancelled);

// setInterval repeats until cleared
let ticks = 0;
const id = setInterval(() => {
  ticks++;
  console.log(t(), "tick", ticks);
  if (ticks === 3) {
    clearInterval(id);
    console.log(t(), "interval stopped");
  }
}, 200);

// A delay of 0 still waits until the current code has finished
setTimeout(() => console.log(t(), "zero-delay timeout"), 0);
console.log(t(), "end of script");

Output

0ms end of script
0ms zero-delay timeout
100ms timeout 100 done
200ms tick 1
300ms timeout 300 done
400ms tick 2
600ms tick 3
600ms interval stopped
  • setTimeout(fn, ms) schedules fn to run once after about ms milliseconds and returns an ID. The script does not stop and wait: “end of script” prints first.
  • Timers run in order of their due time, not the order they were created, so the 100ms timeout fires before the 300ms one.
  • clearTimeout(id) cancels a timer that has not run yet. The cancelled message never appears.
  • setInterval(fn, ms) repeats every ms milliseconds until clearInterval(id) is called. Forgetting to clear an interval leaves it running forever.
  • A delay of 0 does not mean “now”. The callback waits until the current script has finished, which is why it prints after “end of script”.
  • The delay is a minimum. If the program is busy, a timer can fire later than requested, so never use timers for exact timekeeping. Compare against Date.now() instead, as this example does.

Timers with Promises

"use strict";
// A promise-based sleep lets you pause inside async functions
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// Countdown with a for loop and await
async function countdown(from) {
  for (let n = from; n > 0; n--) {
    console.log(`${n}...`);
    await sleep(100);
  }
  console.log("Exam starts now!");
}

// A timeout for slow work: whichever promise settles first wins
function withTimeout(promise, ms) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

// Retry with a growing wait between attempts
async function retry(task, attempts) {
  for (let i = 1; i <= attempts; i++) {
    try {
      return await task(i);
    } catch (e) {
      console.log(`attempt ${i} failed: ${e.message}`);
      if (i === attempts) throw e;
      await sleep(50 * i);
    }
  }
}

async function main() {
  await countdown(3);
  console.log(await withTimeout(sleep(50).then(() => "fast result"), 200));
  try {
    await withTimeout(sleep(500), 200);
  } catch (e) {
    console.log("Error:", e.message);
  }
  const result = await retry(async n => {
    if (n < 3) throw new Error("server busy");
    return "saved on attempt " + n;
  }, 4);
  console.log(result);
}
main();

Output

3...
2...
1...
Exam starts now!
fast result
Error: timed out after 200ms
attempt 1 failed: server busy
attempt 2 failed: server busy
saved on attempt 3
  • sleep(ms) wraps setTimeout in a promise. Inside an async function, await sleep(100) pauses that function without freezing the rest of the program.
  • The countdown loop reads like ordinary step-by-step code, which is much clearer than nesting several setTimeout calls.
  • withTimeout races the real work against a timer that rejects. Promise.race settles with whichever finishes first. The fast job wins its race; the slow one loses and becomes an error. finally clears the timer so it does not linger.
  • retry tries a task several times, waiting a little longer after each failure. This pattern, called backoff, is common for network requests to busy servers.

Timer Functions

FunctionDoes
setTimeout(fn, ms, ...args)Run fn once after at least ms; returns an ID
clearTimeout(id)Cancel a pending timeout
setInterval(fn, ms)Run fn every ms; returns an ID
clearInterval(id)Stop an interval
requestAnimationFrame(fn)Run fn before the next screen repaint (browser animations)
AbortSignal.timeout(ms)A signal that cancels fetch after ms

Common Mistakes

  1. Calling the function instead of passing it: setTimeout(show(), 1000) runs show immediately. Write setTimeout(show, 1000) or use an arrow function.
  2. Never clearing intervals, especially when a page section or component is removed.
  3. Using a loop of timeouts for animation. requestAnimationFrame or CSS animations are smoother.
  4. Expecting await inside forEach to wait. Use a for...of loop, as the countdown does.

Practice Exercises

Exercise 1. Print “Saved!” and then remove the message after 2 seconds, in the browser.

Show answer
const msg = document.getElementById("status");
msg.textContent = "Saved!";
setTimeout(() => { msg.textContent = ""; }, 2000);

Exercise 2. Write a clock that prints the time every second, and stops after 5 ticks.

Show answer
let n = 0;
const id = setInterval(() => {
  console.log(new Date().toLocaleTimeString());
  if (++n === 5) clearInterval(id);
}, 1000);

Frequently Asked Questions

Why do my timers run slowly in a background tab?

Browsers slow down timers in hidden tabs to save battery, often to once per second or less. Code that needs accurate elapsed time should measure it with Date.now() or performance.now() instead of counting ticks.

Is setInterval or a repeated setTimeout better?

A setTimeout that schedules the next one when it finishes guarantees a full gap between runs, even if each run is slow. setInterval fires on a fixed schedule, so slow callbacks can bunch up. For network polling, the repeated setTimeout is usually safer.

Summary

  • setTimeout runs once; setInterval repeats; both return an ID for clearing.
  • Delays are minimums, and even 0 waits for the current code to finish.
  • await sleep(ms) pauses an async function cleanly.
  • Promise.race adds timeouts; retry with growing delays for flaky work.

Next: Type Conversion and == vs ===.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *