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:
Implementation:
To create our timer, we use the following steps:
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); };
The HTML:
<div>Registration closes in <span>
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!