Unit 7 ยท JavaScript

7.8.5Scheduling: setTimeout, setInterval, clearInterval

JavaScript
// Run once after a delay (milliseconds)
const id = setTimeout(() => {
  console.log('3 seconds later');
}, 3000);
clearTimeout(id);                  // cancel before it runs

// Run repeatedly
let seconds = 0;
const timer = setInterval(() => {
  seconds++;
  document.getElementById('clock').textContent = seconds;
  if (seconds === 10) clearInterval(timer);   // stop the repeating
}, 1000);

// Real clock
setInterval(() => {
  document.getElementById('clock').textContent = new Date().toLocaleTimeString();
}, 1000);

Try it (DOM lab)

  1. To-do list: a text box and Add button; each task is an li; clicking a task toggles strike-through; a Delete button on each item.
  2. Countdown timer: user enters seconds, Start/Stop buttons using setInterval.
  3. Image slideshow: array of image paths, Next/Previous buttons, automatic change every 3 seconds.
  4. Dark mode toggle: a button toggling a dark class on body.

Check yourself. The questions for this part are on the 7.11 Review Questions page, with answers to check your work.