IntermediateLesson 17 of 305 min read

Timers: setTimeout, setInterval and animation

Run code later or repeatedly with setTimeout and setInterval, and learn debounce, clocks and requestAnimationFrame.

In this lesson you will

  • Schedule code with setTimeout
  • Repeat code with setInterval and stop it
  • Build a countdown and a clock
  • Use debounce for search boxes

About 18 minutes

Doing things later, and doing them again

Sometimes you want a message to disappear after three seconds, a clock to update every second, or a slideshow to move on by itself. The browser provides timers for exactly this. A timer says: “wait this long, then run this function”. While it waits, the page keeps working normally, which is one of JavaScript’s most important ideas.

setTimeout: run once, later

console.log("First");

setTimeout(() => {
  console.log("Three seconds later");
}, 3000);

console.log("Second");   // prints before the timeout message

setTimeout(function, milliseconds) schedules the function and moves on immediately. Notice the output order: First, Second, and only then, three seconds later, the timeout message. The program did not stop and wait. That is called asynchronous behaviour. 1000 milliseconds equal one second.

Predict the order of the three messages, then press Run to check. Then change the delay on the last one to 0 and predict again.

console.log('A');
setTimeout(() => console.log('B (after 1 second)'), 1000);
setTimeout(() => console.log('C (after 0 seconds)'), 0);
console.log('D');

Even a delay of 0 runs after the current code finishes. Expected: A D C B.

console.log('A');
setTimeout(() => console.log('B (after 1 second)'), 1000);
setTimeout(() => console.log('C (after 0 seconds)'), 0);
console.log('D');
Good to know

Even setTimeout(fn, 0) waits until the current code finishes. The browser keeps a queue of waiting tasks and runs them only when the main flow is free. That is why a long loop can freeze the whole page: nothing in the queue gets a turn.

setInterval: repeat

let seconds = 0;

const timer = setInterval(() => {
  seconds++;
  console.log(seconds);
  if (seconds === 5) {
    clearInterval(timer);      // stop it
    console.log("Done");
  }
}, 1000);

setInterval repeats forever until you cancel it with clearInterval and the id it returned. Likewise clearTimeout cancels a timeout that has not yet run. Always save the id so you can stop the timer.

Build a countdown that starts at 5, updates the display every second, stops at 0 and shows ‘Go!’.

<style>body{font-family:Arial;text-align:center;padding:20px} #n{font-size:64px;font-weight:800;color:#5A28C8}</style>
<div id="n">5</div>
<button id="start">Start</button>
<script>
  const n = document.getElementById('n');
  let left = 5;
  document.getElementById('start').addEventListener('click', function () {
    // use setInterval to count down and clear it at 0
  });
</script>

const id = setInterval(() => { left–; … if (left === 0) { clearInterval(id); n.textContent = ‘Go!’; } }, 1000);

<style>body{font-family:Arial;text-align:center;padding:20px} #n{font-size:64px;font-weight:800;color:#5A28C8}</style>
<div id="n">5</div>
<button id="start">Start</button>
<script>
  const n = document.getElementById('n');
  let left = 5;
  let running = null;
  document.getElementById('start').addEventListener('click', function () {
    if (running) return;
    running = setInterval(function () {
      left--;
      if (left <= 0) {
        clearInterval(running);
        n.textContent = 'Go!';
      } else {
        n.textContent = left;
      }
    }, 1000);
  });
</script>

Useful timer patterns

1. Hide a message automatically

function toast(message) {
  const box = document.querySelector("#toast");
  box.textContent = message;
  box.hidden = false;
  setTimeout(() => { box.hidden = true; }, 3000);
}

2. Debounce: wait until the user stops

function debounce(fn, delay) {
  let id;
  return (...args) => {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), delay);
  };
}

const search = debounce((text) => console.log("Searching for", text), 400);
input.addEventListener("input", (e) => search(e.target.value));

Without debounce, typing “javascript” would trigger ten searches. With it, the search runs once, 400 milliseconds after the last key. Every professional site uses this idea for search boxes, resize handlers and auto-save.

3. A live clock

Show the current time and update it every second. Format it with toLocaleTimeString.

<style>body{font-family:Arial;text-align:center;padding:24px} #c{font-size:42px;font-weight:800;color:#5A28C8}</style>
<div id="c"></div>
<script>
  const c = document.getElementById('c');
  function tick() {
    // set c.textContent to the current time
  }
  tick();
  setInterval(tick, 1000);
</script>

c.textContent = new Date().toLocaleTimeString();

<style>body{font-family:Arial;text-align:center;padding:24px} #c{font-size:42px;font-weight:800;color:#5A28C8}</style>
<div id="c"></div>
<script>
  const c = document.getElementById('c');
  function tick() {
    c.textContent = new Date().toLocaleTimeString();
  }
  tick();
  setInterval(tick, 1000);
</script>

requestAnimationFrame: smooth animation

let x = 0;
const box = document.querySelector(".box");

function move() {
  x += 2;
  box.style.transform = `translateX(${x}px)`;
  if (x < 300) requestAnimationFrame(move);
}
requestAnimationFrame(move);

For visual animation, requestAnimationFrame is better than setInterval because it runs just before the screen repaints, usually 60 times a second, and pauses automatically in hidden tabs. For simple movement, though, CSS transitions and animations are even better; you studied them in the CSS course.

Dates and times

const now = new Date();
console.log(now.getFullYear(), now.getMonth() + 1, now.getDate());  // month starts at 0!
console.log(now.getHours(), now.getMinutes());
console.log(now.toLocaleDateString("en-GB"));
console.log(Date.now());      // milliseconds since 1970
Common mistake

Starting an interval and never clearing it. Every click on a Start button would start a new timer on top of the old one, and the countdown would run twice as fast. Store the id and check it, or clear the previous timer first.

Timers are not exact

Browsers can delay timers slightly, and tabs in the background may run them only once a second. For accurate stopwatches, compare Date.now() to the start time instead of counting ticks.

Worked example: an auto-advancing slideshow

A slideshow is a timer plus an index. Every few seconds the index moves to the next slide, wrapping back to zero at the end, and the matching slide gets the visible class. The wrap-around uses the remainder operator you learned earlier.

const slides = document.querySelectorAll(".slide");
let current = 0;

function show(i) {
  slides.forEach((s, n) => s.classList.toggle("active", n === i));
}

setInterval(() => {
  current = (current + 1) % slides.length;
  show(current);
}, 3000);

show(0);

The key line is (current + 1) % slides.length. With three slides, the index goes 0, 1, 2, then back to 0 and never runs off the end. Add buttons that change current yourself, and you have a full slider. Remember to pause the show when someone hovers over it, which is both friendlier and better for accessibility: clear the timer on mouseenter and start a fresh one on mouseleave.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which runs a function once after a delay?

  1. setInterval
  2. repeat
  3. setTimeout
  4. wait

setTimeout runs once.

How long is setTimeout(fn, 2000)?

  1. 2 seconds
  2. 2 milliseconds
  3. 20 seconds
  4. 2 minutes

Time is in milliseconds.

How do you stop a setInterval?

  1. stop()
  2. break
  3. clearInterval(id)
  4. delete id

Save the id and clear it.

What is debounce for?

  1. Waiting until the user stops before running code
  2. Making code faster always
  3. Deleting timers
  4. Sorting arrays

It avoids running on every keystroke.

In what order does this print: A, setTimeout(B, 0), C?

  1. A B C
  2. A C B
  3. B A C
  4. C B A

Timeout callbacks wait until the current code finishes.

Summary

  • setTimeout runs once, setInterval repeats.
  • Always keep the id so you can clear timers.
  • Timers are asynchronous: the page keeps running.
  • Debounce waits until the user stops typing.

Next lesson

Next: localStorage, remembering data after the page closes.

Questions

Why does setTimeout with 0 not run immediately?

It waits until the current code finishes, because tasks run in a queue.

Are timers accurate?

Roughly. For exact timing, compare Date.now() with a start time.

Should I use setInterval for animation?

Prefer CSS animations or requestAnimationFrame for smooth visuals.

Progress is saved in this browser.