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
- Create an HTML file with a
<h1>tag to display the countdown (e.g.,<h1 id="countdown"></h1>). - Add a button to start the countdown (e.g.,
<button id="startButton">Start</button>).
JavaScript
Write JavaScript code to:
- Get references to the
<h1>and the button usingdocument.getElementById(). - Create a variable to store the starting time (e.g., 10 seconds).
- Add an event listener to the button that starts the countdown when clicked.
- Inside the event listener:
- Use
setInterval()to decrement the countdown every second. - Update the
<h1>tag with the remaining time. - Use
setTimeout()to stop the countdown when it reaches 0. - Display a message like "Time's up!" when the countdown ends.
- Use
Bonus Challenges
- Add a "Pause/Resume" button to control the countdown.
- Allow the user to input a custom starting time.
- Style the countdown timer with CSS to make it visually appealing.
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);
});