countdown minute timer javascript code example
Example 1: countdown in javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Countdown timer using HTML and JavaScript</title>
</head>
<body>
Registration closes in <span id="timer">05:00<span> minutes!
<!-- custom js -->
<script>
window.onload = function () {
var minute = 5;
var sec = 60;
setInterval(function () {
document.getElementById("timer").innerHTML =
minute + " : " + sec;
sec--;
if (sec == 00) {
minute--;
sec = 60;
if (minute == 0) {
minute = 5;
}
}
}, 1000);
};
</script>
</body>
</html>
Example 2: countdown in js
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);
};