Home >Web Front-end >JS Tutorial >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:
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!