Home > Web Front-end > JS Tutorial > How to Build a Simple Countdown Timer Using Only Vanilla JavaScript?

How to Build a Simple Countdown Timer Using Only Vanilla JavaScript?

Linda Hamilton
Release: 2024-12-02 07:27:11
Original
194 people have browsed it

How to Build a Simple Countdown Timer Using Only Vanilla JavaScript?

Creating a Simple Countdown Timer with Vanilla JavaScript

In web development, it's often necessary to implement countdown timers. While various solutions exist, beginners may find them excessively complex. This article demonstrates how to create a simple, non-jQuery countdown timer in JavaScript using a vanilla implementation.

The Goal: Create a countdown timer that:

  • Counts down from "05:00" to "00:00".
  • Resets to "05:00" after reaching "00:00".
  • Avoids complex functions like Date objects.

Implementation:

To create our timer, we use the following steps:

  1. Define the startTimer function: This function takes two parameters: the duration (in seconds) and the display element to update.
  2. Initialize the timer and variables: We set the timer to the provided duration and calculate the initial minutes and seconds.
  3. Use setInterval to update the display: Every second, we recalculate the minutes and seconds, format them with leading zeros if needed, and update the display element.
  4. Reset the timer on reaching 0: After each decrement, we check if the timer has reached 0 and reset it if necessary.

The Code:

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

The HTML:

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

This code creates a countdown timer that updates the display element with the remaining time every second. When the timer reaches 00:00, it resets to 05:00.

The above is the detailed content of How to Build a Simple Countdown Timer Using Only Vanilla 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