Home >Web Front-end >JS Tutorial >How Can I Create a Simple JavaScript Countdown Timer?

How Can I Create a Simple JavaScript Countdown Timer?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 09:20:10680browse

How Can I Create a Simple JavaScript Countdown Timer?

Creating a Simple JavaScript Countdown Timer

Your query about creating a minimalist countdown timer is a common one in web development. Let's break down the steps involved in achieving this.

Vanilla JavaScript Approach:

For your specific requirement of displaying a timer that counts down from "05:00" to "00:00" and resets, you can employ the following approach using vanilla JavaScript:

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};

In this script:

  • duration specifies the initial countdown time in seconds (here, 5 minutes).
  • display is an HTML element that will show the countdown.
  • setInterval executes the timer logic every second (1000 milliseconds).
  • Inside the timer, parseInt is used to convert the remaining time into minutes and seconds.
  • The displayed strings are padded with zeros to maintain the "05:00" format.
  • When the timer reaches 0, it resets back to duration.

Additional Features:

If desired, you can extend the functionality with features such as a start/stop button:

<button>
document.getElementById("start").addEventListener("click", function () {
    // Start the timer...
});

document.getElementById("stop").addEventListener("click", function () {
    // Stop the timer...
});

The above is the detailed content of How Can I Create a Simple JavaScript Countdown Timer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn