10 Second Countdown Timer using JavaScript
In this article, we will create a 10 second countdown timer using JavaScript. This timer can be used for various purposes such as quizzes, games, or any other application that requires a countdown.
HTML Structure
First, let's create the HTML structure for our countdown timer. We will create a div
element to display the countdown timer.
JavaScript Code
Now, let's write the JavaScript code to create the countdown timer.
const countdownTimer = document.getElementById('countdown-timer');
let seconds = 10;
function countdown() {
if (seconds > 0) {
seconds--;
countdownTimer.innerHTML = `Time remaining: ${seconds} seconds`;
setTimeout(countdown, 1000);
} else {
countdownTimer.innerHTML = 'Time\'s up!';
}
}
countdown();
How it Works
Here's how the code works:
- We first get a reference to the
div
element usingdocument.getElementById
. - We initialize a variable
seconds
to 10, which is the initial countdown time. - The
countdown
function is called recursively usingsetTimeout
every 1000 milliseconds (1 second). - Inside the
countdown
function, we decrement theseconds
variable and update the HTML content of thediv
element to display the remaining time. - If
seconds
is greater than 0, we call thecountdown
function again after 1 second. Otherwise, we display the message "Time's up!".
Demo
You can see a live demo of the countdown timer .
Conclusion
In this article, we created a simple 10 second countdown timer using JavaScript. This timer can be easily customized to fit your needs. You can change the initial countdown time, update the display message, or add additional functionality to the timer.