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

How to Create a Simple Countdown Timer Using Only JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 22:31:16522browse

How to Create a Simple Countdown Timer Using Only JavaScript?

Creating a Simplistic Countdown Timer in JavaScript

If you seek to establish a straightforward countdown timer for your website, one that gracefully transitions from "05:00" to "00:00," look no further. This article offers a streamlined solution that foregoes complex Date objects, ensuring utmost simplicity.

JavaScript-Only Timer

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);
};

HTML Structure:

<body>
  <div>Registration closes in <span>

The above is the detailed content of How to Create a Simple Countdown Timer Using Only JavaScript?. 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