Home > Web Front-end > JS Tutorial > How to Create a Simple 5-Minute Countdown Timer in JavaScript?

How to Create a Simple 5-Minute Countdown Timer in JavaScript?

Barbara Streisand
Release: 2024-12-05 12:04:10
Original
374 people have browsed it

How to Create a Simple 5-Minute Countdown Timer in JavaScript?

Creating a Basic Countdown Timer in JavaScript

Problem:

Seeking a simple JavaScript solution to implement a countdown timer that displays "Registration closes in 05:00 minutes!" and counts down to "00:00" before resetting to "05:00."

Solution:

To avoid date functions, we present two approaches:

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);
};
Copy after login

HTML:

<body>
    <div>Registration closes in <span>
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template