10 Second Countdown Timer Javascript

3 min read Jun 20, 2024
10 Second Countdown Timer Javascript

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:

  1. We first get a reference to the div element using document.getElementById.
  2. We initialize a variable seconds to 10, which is the initial countdown time.
  3. The countdown function is called recursively using setTimeout every 1000 milliseconds (1 second).
  4. Inside the countdown function, we decrement the seconds variable and update the HTML content of the div element to display the remaining time.
  5. If seconds is greater than 0, we call the countdown 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.