Creating a Simple JavaScript Countdown Timer
Implementing a countdown timer in JavaScript can be straightforward, even without utilizing complex Date objects. Here's a simplified guide to creating a simple countdown timer:
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); };
This code establishes a timer variable set to the desired duration in seconds (in this case, 5 minutes) and updates a display element with the remaining time. It refreshes every second, decrementing the timer each time and displaying the formatted minutes and seconds. Once the time elapses, the timer resets to the initial duration.
jQuery Option (with Start/Stop Button)
For a version with a start/stop button:
$(function () { var timer = 60 * 5, display = $("#time"), interval; $("#start").click(function () { interval = setInterval(function () { var minutes = Math.floor(timer / 60), seconds = timer % 60; minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.text(minutes + ":" + seconds); timer--; if (timer < 0) { clearInterval(interval); timer = 60 * 5; } }, 1000); }); $("#stop").click(function () { clearInterval(interval); }); });
This version includes a start button that initiates the timer and a stop button that pauses it. It uses jQuery for convenience, simplifying the manipulation of DOM elements.
The above is the detailed content of How to Create a Simple JavaScript Countdown Timer with and without jQuery?. For more information, please follow other related articles on the PHP Chinese website!