WDD 330: Web Frontend Development II

W02 Learning Activity: setTimeout / setInterval

Overview

Sometimes you will want to execute a function after a certain amount of time has passed and not immediately. For example, you may want to delay the execution of a function until after a user has finished typing in an input field. This is where the setTimeout() and setInterval() methods are useful.

In this activity, you will discover how to create timed events in a web applications.

Prepare

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.

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); 
});