How to write a countdown timer in JavaScript?
I have two demos, one with jQuery
and one without. Neither use date functions and are about as simple as it gets.
Demo with 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);
};
<body>
<div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>
Creating a Countdown with JavaScript
I would use a setInterval()
for a simple countdown timer. I would also write my function for the math loop outside of the setInterval and then call on the function within the interval, like the following => setInterval(timerFunction(), 1000)
. There is no need for a loop when you use the interval, it does the looping each defined time increment as set in your setInterval()
. Each time the interval fires, the function will do its thing.
EDIT: added a conditional to see if the interval time has run out.
I have included an example of a simple count down timer in my answer below along with notation inside the code that helps to explain further. Hope this helps.
Also, by terminal, I assume you mean the console? My example displays the setInterval in the console...
let sMin = 2; // amount of minutes you wish to start with
let time = sMin * 60; // format for minutes by multiplying by 60 as we have 60 seconds in each minute
let countdown = setInterval(update, 1000) // set up a setInterval for the countdown function
// create a function that will countdown the seconds
function update() {
// define our minutes using Math.floor(time / 60)
let min = Math.floor(time / 60);
// define our seconds by modulating time with 60, our seconds units
let sec = time % 60;
// tenerary conditional to see if seconds is set to 0 for proper display of formatting as seconds
sec = sec < 10 ? '0' + sec : sec;
// display the countdown timer in time format using the minutes and seconds variables
console.log(`${min}:${sec}`);
// decrement time by one second with each interval as set in the setInterval call `1000`
time--;
// clear the interval if the minutes and seconds are both set to 0
min == 0 && sec == 0 ? clearInterval(countdown) : countdown;
}
Create a simple 10 second countdown
JavaScript has built in to it a function called setInterval
, which takes two arguments - a function, callback
and an integer, timeout
. When called, setInterval
will call the function you give it every timeout
milliseconds.
For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.
function makeAlert(){
alert("Popup window!");
};
setInterval(makeAlert, 500);
However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.
setInterval(function(){ alert("Popup window!"); }, 500);
Once setInterval
is called, it will run until you call clearInterval
on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.
var timeleft = 10;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
}
document.getElementById("progressBar").value = 10 - timeleft;
timeleft -= 1;
}, 1000);
<progress value="0" max="10" id="progressBar"></progress>
How to create a set countdown timer in Javascript?
This should do the job:
function itemHandler(){
var label = document.getElementById('item1-label');
if (label.innerHTML == "") {
var countdown = 10;
label.innerHTML = `Time Remaining: ${countdown}`;
var countdownInterval = setInterval(function() {
if (countdown > 0) {
label.innerHTML = `Time Remaining: ${countdown}`;
countdown -= 1;
}
}, 1000);
} else {
clearInterval(countdownInterval);
label.innerHTML = '';
}
}
First program: javascript countdown timer
setTimeout
take function name and it will if
not while
and change the text within function
.
var timer = 60;
function updatePLEASE() {
timer--;
if (timer > 0){
//console.log(timer);
document.getElementById("myTimer").innerHTML = timer;
setTimeout(updatePLEASE, 1000); /* replicate wait 1 second */
}
}
updatePLEASE();
<p id="myTimer">Blank Text</p>
JavaScript countdown timer for hour, minutes and seconds when a start button click
Working Code:
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>
Related Topics
Changing the Image Source Using Jquery
How to Update the Parent'S State in React
How to Read and Write into File Using JavaScript
Typeerror: $(...).Modal Is Not a Function with Bootstrap Modal
Event Listener on a CSS Pseudo-Element, Such as ::After and ::Before
Batch File > JavaScript > Winscp > Check If File Exists
Mocha/Chai Expect.To.Throw Not Catching Thrown Errors
Correct JavaScript Inheritance
How to Set the Caret (Cursor) Position in a Contenteditable Element (Div)
Converting a Js Object to an Array Using Jquery
Variable Name as a String in JavaScript
Jspdf Can't Get Any Styling to Work
How to Concatenate and Minify Multiple CSS and JavaScript Files with Grunt.Js (0.3.X)
Detect CSS Transitions Using JavaScript (And Without Modernizr)