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
- Read: 📃 Scheduling: setTimeout and setInterval - JavaScript.info
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);
});