WDD 330: Web Frontend Development II

setTimeout and setInterval

Overview

The setTimeout() and setInterval() methods are part of the Window object. They are used to schedule code execution at a later time. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

"We may decide to execute a function not right now, but at a certain time later. That’s called “scheduling a call”." - JavaScript.info

Prepare

  1. Read: 📃 Scheduling: setTimeout and setInterval - JavaScript.info

Activity Instructions

Practice using setTimeout() and setInterval() to create a countdown timer in JavaScript.

HTML

JavaScript

Write JavaScript code to:

Bonus Challenges

Partial Sample Solution
const countdownDisplay = document.getElementById('countdown');
const startButton = document.getElementById('startButton');

let timeLeft = 10;

startButton.addEventListener('click', () => {
  setInterval(() => {
    if (timeLeft >= 0) {
      countdownDisplay.textContent = timeLeft;
      timeLeft--;
    } else {
      // Stop the countdown and display a message
    }
  }, 1000); 
});