Simple countdown timer using javascript
Posted by navaneeth on Jun 26, 2013 in HTML, Javascript | 106 Comments

we can create an simple countdown timer using javascript without any javascript library
for that first we need to create an html element with the following
<div id="timer">2:00</div>
And add the javacript code from below
<script type="text/javascript"> var timeoutHandle; function countdown(minutes) { var seconds = 60; var mins = minutes function tick() { var counter = document.getElementById("timer"); var current_minutes = mins-1 seconds--; counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds); if( seconds > 0 ) { timeoutHandle=setTimeout(tick, 1000); } else { if(mins > 1){ // countdown(mins-1); never reach β00β³ issue solved:Contributed by Victor Streithorst setTimeout(function () { countdown(mins - 1); }, 1000); } } } tick(); } countdown(2); </script>
countdown(2) is the function which invokes the timer and the minutes as the only parameter
and we are done!
The working example is shown below
Hope this helps to create simple countdown timer using javascript without any javascript library
As per the request from Steve i am adding the timer functionality in the format H:M:S
<div id="hms">00:10:10</div>
And add the javacript code from below
<script type="text/javascript"> var timeoutHandle; function count() { var startTime = document.getElementById('hms').innerHTML; var pieces = startTime.split(":"); var time = new Date(); time.setHours(pieces[0]); time.setMinutes(pieces[1]); time.setSeconds(pieces[2]); var timedif = new Date(time.valueOf() - 1000); var newtime = timedif.toTimeString().split(" ")[0]; document.getElementById('hms').innerHTML=newtime; timeoutHandle=setTimeout(count, 1000); } count(); </script>
The working example is shown below
For the timer to continue on page refresh, you can use this code to store the time in cache and reuse that to start the timer
var timeoutHandle; function countdown(minutes,stat) { var seconds = 60; var mins = minutes; if(getCookie("minutes")&&getCookie("seconds")&&stat) { var seconds = getCookie("seconds"); var mins = getCookie("minutes"); } function tick() { var counter = document.getElementById("timer"); setCookie("minutes",mins,10) setCookie("seconds",seconds,10) var current_minutes = mins-1 seconds--; counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds); //save the time in cookie if( seconds > 0 ) { timeoutHandle=setTimeout(tick, 1000); } else { if(mins > 1){ // countdown(mins-1); never reach β00β³ issue solved:Contributed by Victor Streithorst setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000); } } } tick(); } function setCookie(cname,cvalue,exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } countdown(2,true);
106 Comments on “Simple countdown timer using javascript”
Rahul
October 11, 2013simply great..
Rogara
February 8, 2014Great, thanks a lot. π
Victor Streithorst
February 10, 2014I don’t know if somebody else noticed this too, but the seconds never reach “00”. It jumps from “5:01” directly to “4:59”.
I just changed the line:
‘ countdown(mins-1); ‘
to:
‘ setTimeout(function () { countdown(mins – 1); }, 1000); ‘
, and everything works like a charm now!
Anyway, thank you! Your code saved me a lot of time!
navi
February 11, 2014Thank you for you feedback and contribution
akshata.akkanna@gmail.com
October 20, 2016Hello
I have copy pasted the same code as you did but im getting just the constant value like 2:00
navaneeth
October 25, 2016Please check the code again or paste them here
Brian Cooney
July 1, 2017I had the same issue. My javascript code was running before the DOM was constructed. Make sure your script tag in HTML is after the CSS link.
Wrap this around your code so it waits for DOM construction.
window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
}
Hope that helps others out:)
Todor
April 19, 2014Great countdown!
Can you please show how to increase the timer so it’s set for more than 2 minutes, maybe even hours and days? Thanks!
Steve
May 15, 2014This is great. How hard would it be to add a value for Hour? I’m trying to use this to for a 24 hour counter H:M:S
navi
June 26, 2014see the last section i added the code to show the format H:M:S
https://navaneeth.me/simple-countdown-timer-using-javascript
Manish Prabhakar
August 12, 2014How to remove the timer when it reaches 0?
navi
August 12, 2014Remove means?, Is this to remove the entire timer
Inorder to add text when the timer expires please use this code
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(":");
var time = new Date(); time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newtime;
if(newtime!=='00:00:00'){
setTimeout(count, 1000);
}else
{
document.getElementById('hms').innerHTML='Ended';
}
}
count();
Kanishk Grover
April 6, 2017how to disable and enable a button when the timer gets over?
Stan
June 20, 2017This code is exactly what I need. However, where do I put the code in to change the timer from 0:00 to a message of my choice?
Regards
Ang
December 11, 2014This is great!! Thank you so much for this!!! π
Simon
December 19, 2014Thank you for this, it has really helped.
Rushan
January 6, 2015Excellant article…really helped us
lev
March 29, 2015is it posible to use it for each news with different countdown? like getting time from db. i tryed it but works only for first news.
navaneeth
March 30, 2015You can use different id’s for the timer container to work that for multiple elements
lev
March 30, 2015yes but i mean use for 50, 100+ news and thats bad idea use different id’s. there’s any method to use foreach() function like php on javascript?
navaneeth
April 1, 2015Just make the id to class ie “hms” and the html has to be repeated and just call the javascript function in a for loop or for each loop
Marie
March 30, 2015Very informative article
prathysha
June 8, 2015how to continue the same timer on page reload
navaneeth
June 8, 2015Have to store the current time in session or cookie, then use that when reload happens
priyanka
June 15, 2015can you give me the code for timer using local storage
priyanka
June 16, 2015please give me the code for timer using local storage
navaneeth
June 17, 2015you can use this code to store the time in cache and reuse that to start the timer
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if(getCookie("minutes")&&getCookie("seconds"))
{
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes",mins,10)
setCookie("seconds",seconds,10)
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds); //save the time in cookie if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach β00β³ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i
raunit
October 7, 2015time storage to cookie is not working
navaneeth
December 9, 2015can u share me the code you used
priyanka
June 17, 2015above code not getting executed
navaneeth
June 17, 2015Have u copied the whole code??
priyanka
June 17, 2015yeah..i copied
navaneeth
June 17, 2015pls send me the url where u pasted the code
priyanka
June 18, 2015i inserted the code in php program..it is in my pc..
navaneeth
June 18, 2015Can u pls share me the code, so i can look in to it
if you are running it in localhost
you have to set the cookie domain to localhost
priyanka
July 10, 2015i am unable to post the code..can please give the whole program
navaneeth
September 10, 2015Added the code to the last part of the post
raja
July 14, 2015i need local storage timer countdown please send me immediately.
navaneeth
September 10, 2015Added the code to the last part of the post
Janis
September 1, 2015Hello, i intrested if its posoble and if is, you can plz tell how it do:?
i whant make a php table wheri is listed a links, ect. whanted to set up cooldown time when i press a web page its aper to that link and start coldowntime from 2min, 4, 7, 20, 60, of eny links have eny colldowtime, and its starts only when i cliked the link, and apers in my page link table in section time left, when get to 0 its disapear(timer).
navaneeth
September 10, 2015Explain pls, i cant get what you meant
Aiswariya
September 10, 2015The timer code is perfect ,but when i refresh my page its starts from first,i have to implement in my shopping site,Is there any solutions???
navaneeth
September 10, 2015You have to store the values in database
Erich Eachann
September 17, 2015Is there a way to have the function execute twice?
I’ve tried all of these but none of them work nicely:
—————
countdown(value1)
countdown(value2)
—————
$.when(countdown(value1)).then(countdown(value2));
—————
$.when(countdown(work))
.then(
setTimeout(function() {
alert(‘value2!’);
countdown(value2);
}, 2000))
Any way to get this to work?
Erich Eachann
September 17, 2015In other words,
how do you wait for a first timer, then reset it and have a second timer execute?
navaneeth
September 17, 2015HI
Wait for the timer to complete and call another function when the time reaches 0
Erich Eachann
September 17, 2015How do you integrate that in the original function (what code do I need)?
Madhu
October 21, 2015In the 1st script, I changed 2, to 5 or 8.
But the time always starts from 2:00
navaneeth
December 9, 2015Share me the code you used
Pol
November 27, 2015Hello, I want to make a start button with audible warning and forward to updating the counter continued to work and did not start the first in a single session. In the third embodiment, like there is the possibility to make it through cookies for a day, but my knowledge is too small to make this code work – you could not see when you have free time? https://jsfiddle.net/HRrYG/
dragonflai
December 3, 2015Great work navaneeth, but i have some problem with your ‘cache’ version. I,ve used as is written but don’t work properly. Can you check or explain where i do a mnistake.
please note: if you want add a reloading you can simple change this lines:
instead of:
document.getElementById(‘hms’).innerHTML=’Ended’;
change with:
document.getElementById(‘hms’).innerHTML=’Reloading Page…’;
document.location.reload(true);
on reload the counter is reset automatically. (reload all the page) π
— true of false – Is a Boolean flag, which, when it is true,
causes the page to always be reloaded from the server.
If it is false or not specified, the browser may reload the page from its cache.
Joe
December 7, 2015Hello Navaneeth,
Just wondering why my timer stops after 1 minute.
If I make it to count for 2 minutes it stops at 1:00
If I make it to count for 60 minutes it stops at 59:00
I am using the last code with cookies to store the count on page reload..thanks for help!
Joe
December 7, 2015Hello Navaneeth,
Just wondering why my timer stops after 1 minute.
If I make it to count for 2 minutes it stops at 1:00
If I make it to count for 60 minutes it stops at 59:00
I am using the last code with cookies to store the count on page reload..thanks for help!
raju
January 14, 2016Your cache version is not executing.. the time is refreshing on page reload…..can u please post the executed code…
navaneeth
March 16, 2016are you trying it on local?
gabriel
February 26, 2016how to alert my user to finish countdown?
navaneeth
March 17, 2016Just check the seconds if it has reached 0
SuperPiglet
January 1, 2018How to check if minutes and seconds are at zero (ie – the countdown has finished). The following code isn’t working
if((seconds == 0) && (mins == 0))
{
alert(“Game Over – You Ran Out of Time”);
}
SuperPiglet
January 1, 2018Answered my own question. Here is the Answer
if((seconds == 0) && (current_minutes == 0))
{
alert(“Game Over – You Ran Out of Time”);
}
Seemanta Bhowmick
March 26, 2016Hey there, the timer seems to stops at 1:00, if I set it to 2:00? Can you please help me out in solving this issue.. I’m a beginner at all this, so I would also like to know where and what code can I add to move a different page (say as moving to a result page, if exam time is up) when the timer is up?
Thank you..any help would be really appreciated!
navaneeth
April 2, 2016Pls post the code here, or mail me, will help you with this
Nad
May 20, 2016pls, when I try using For the timer to continue on page refresh, you can use this code to store the time in cache and reuse that to start the timer, the countdown just stop
navaneeth
May 23, 2016i have updated the code, please check now
d laxmi
November 14, 2016hiiii i need for the following code the time has been set to 1 min i need to set it for 2mins please help me i will send u the code here
function isTimer(seconds) {
// BUG: page refresh with keyboard triggers onkeyup and starts timer
// Use restart button to reset timer
let time = seconds;
// only set timer once
let one = $(“#timer > span”)[0].innerHTML;
if (one == “1:00″) {
let typingTimer = setInterval(() => {
if (time <= 0) {
clearInterval(typingTimer);
} else {
time -= 1;
let timePad = (time span”)[0].innerHTML = `0:${timePad}`;
}
}, 1000);
}
else if (one == “0:00”) {return false;
}
return true;
}
navaneeth
December 19, 2016The first example shows the time set to 2 mins
phani
July 2, 2016plz send me all code
my:phanikumar294@gmail.com
navaneeth
July 6, 2016which code do you need?
shail desai
July 22, 2016thanks sir ,best help ever..better then any other website.
vicky
July 27, 2016Can you please send me the countdown spot left code
Like i want user to show signup 15 spots left only and countdown slowly decreases its no like 14 after 8 seconds then 13 spots left after 8 or 10 seconds like that
I need a code for such type I will be grateful to you if you can provide me such code
Thanks alot in advance
navaneeth
August 8, 2016Sorry for the delay, do you still need that code?
Nelson C Joseph
August 1, 2016how to reset timer during page refresh?
navaneeth
August 8, 2016Use without the cookie option
eko susilo
August 2, 2016I use your timer to continue on page refresh, but when timer finish then i refresh page, the timer just show 0:00.
01:10
function countdown(minutes,stat) {
var seconds = 60;
var mins = minutes;
if(getCookie(“minutes”)&&getCookie(“seconds”)&&stat)
{
var seconds = getCookie(“seconds”);
var mins = getCookie(“minutes”);
}
function tick() {
var counter = document.getElementById(“timer”);
setCookie(“minutes”,mins,10)
setCookie(“seconds”,seconds,10)
var current_minutes = mins-1
seconds–;
counter.innerHTML =
current_minutes.toString() + “:” + (seconds 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach β00β³ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000);
}
}
}
tick();
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = “expires=” + d.toGMTString();
document.cookie = cname+”=”+cvalue+”; “+expires;
}
function getCookie(cname) {
var name = cname + “=”;
var ca = document.cookie.split(‘;’);
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
countdown(2,true);
navaneeth
August 8, 2016You have to reset the time back to the initial state when it expires, if you need them to work again
Bri
October 22, 2016Could you tell how to reset time?
navaneeth
October 25, 2016Just call the initiation function again
TG
October 29, 2016Please how do i call the initation function again.. am trying it but its not working, please am waiting in anticipation for your favourable response, its urgent..
navaneeth
December 29, 2016I have made small adjustments to the code
Now call this before window.clearTimeout(timeoutHandle); countdown(2); when you want to initiate it again
K.Srinivasa Rao
October 25, 2016God bless you, dear Navi. May your tribe increase! Thank you for what you are doing.
fmoh
November 6, 2016Hi. nice script.
I am using your script “as is”. I was trying to reset the timer by re-initializing the function (like you suggested i.e. countdown(2)), but when doing so, it does two things: 1) it sets a new timer counting down from init value and 2) it keeps old value running down as well. means, it keeps both values flickering downwards on same div container. any clue why this happens?
thanks a lot
GAJENDER
December 2, 2016I WANT TO SET DATE TIMER IN MY PERSONAL WEBPAGE CAN U PL SEND ME CODE
navaneeth
December 19, 2016Just simple one, or get me what exactly you need..
The first section in the page shows a simple one
Jsut create the html
and copy the script and call countdown(2);
Bharath Surendran
January 13, 2017I want a automatically repeating countdown which repeats (or) Resets itself every week ( ie. 7 days ). I also want to display 2 buttons [ with a link to a new page on both of them ] , when timer reaches zer0 [ ie. just before resetting its self . Can you please help me?
BHARATH SURENDRAN
January 12, 2017I want a automatically repeating countdown which repeats (or) Resets itself every week ( ie. 7 days ). I also want to display 2 buttons [ with a link to a new page on both of them ] , when timer reaches zer0 [ ie. just before resetting its self . Can you please help me?
subash
February 4, 2017Hi,
How do i loop the timer ,
for example, the timer runs for 5minutes , after the it stops and an button arrives , after clicking the button (some job is done , may be display an ad for for 1 minutes , like that ),
After that , the timer starts again.
Alarape Rahman
April 15, 2017Thanks navaneeth, Your tutorial has really helped. Meanwhile i wrote this piece of codes for my javascript count down timer, but whenever i reload the page, the count down timer will start from the beginning, i want it to start where it stop whenever i reload my page. this is this code
function timer(){
var countdown = document.getElementById(‘time’);
var dur = countdown.getAttribute(“duration”);
var d1 = new Date(),d2 = new Date(d1);
var time = dur.match(/(\d+)(?::(\d\d))?\s*(p?)/);
d2.setHours( d1.getHours()+(parseInt(time[1]) + (time[3] ? 12 : 0)) );
d2.setMinutes( d1.getMinutes()+(parseInt(time[2]) || 0) );
var end = d2.getTime();
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24;
var timer;
function showRemaining()
{
var now = new Date();
var distance = end – now;
dur = distance;
if (distance 300000){countdown.style.color = “#F90”;}else{countdown.style.color = “#060”;}
if (distance < 300000){
countdown.style.color = "#F00";
}
if (distance < 0 ) {
clearInterval( timer );
timeUp(countdown);
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
countdown.innerHTML = '';
dur = hours+":"+minutes+":"+seconds;
countdown.innerHTML = "Time Left: ";
if (days) {
countdown.innerHTML += 'Day(s): ' + days + '; ';
}
if (hours) {
countdown.innerHTML += hours+ ' Hr.; ';
}
countdown.innerHTML += minutes+ ' Min.; ';
countdown.innerHTML += seconds+' Sec.;';
}
timer = setInterval(showRemaining, 1000);
}
function timeUp(counter){
counter.innerHTML=" TIME UP!!!!!!!!";
}
. please kindly help me
Xp0sed
April 21, 2017Can you please give an example how to get this countdown with instead of div?
And please how to use it when I have stored the time in MySQL database like this; 1492802935.
Thank you alot!
Tofunmi
May 9, 2017Thanks so much for the snippet. Please, How can I set the timer to begin at 30 secs. If I input 0.5 in the countdown(X); the timer starts from -0.5:59.
harish
June 15, 2017can i get code for hours also?
Rati
July 26, 2017Thank you so much for the code! It works great…
Is it possible to add some content (sound or at least notification “You time’s up” or something like that) after timer comes to 0?
Tanks again!
meck
November 26, 2017helo friend plzz tell me how when timer reach to 00 like end then show alert your time is upp soory try again …. how this is possible
Jan te Pas
December 12, 2017I like your scripts. I would like to trigger a Submit after the countdown is ready, so call document.getElementById(βMyForm”).submit(); when the timer reaches 0:00, How can i do that?
This is meaning toe send an list after a certain time. Help is very meedeed.
Jan
December 12, 2017I have added in the code. I have change the DIV so when the button is clicked, only the countdowntime is visible.
Send in 30 minutes
Only, where can i put the command to Submit after the countdown is over?
Regards, jan
Dominik Novicky
December 15, 2017Hello,
Can you help with the code?
I want to add button and on the click start countdown.
Thank You
Rahul
February 8, 2018please help me. can u tell me how to use cache in place of local storage.
var timer;
var d = new Date();
var currentDay = d.getDate();
var timer;
var second; // Total Millisecond In One Sec
var minute; // Total Sec In One Min
var hour; // Total Min In One Hour
var day ;
var end;
function settimer()
{
clearInterval(timer);
var timer_month=document.getElementById(“month”).value;
var timer_hour=document.getElementById(“hour”).value;
if(timer_hour==””)timer_hour=0;
var timer_minu=document.getElementById(“minu”).value;
if(timer_minu==””)timer_minu=0;
var timer_date=timer_month+” “+timer_hour+”:”+timer_minu;;
if(window.localStorage.getItem(‘endDate11’)==null)
{
end = new Date(timer_date); // Arrange values in Date Time Format
}
else
{
end=new Date(window.localStorage.getItem(‘endDate11′));
}
var now = new Date(); // Get Current date time
second = 1000; // Total Millisecond In One Sec
minute = second * 60; // Total Sec In One Min
hour = minute * 60; // Total Min In One Hour
day = hour * 24; // Total Hour In One Day
if(timer_date!=’ 0:0′)
{
end = new Date(timer_date);
window.localStorage.setItem(‘endDate11’,end);
}
showtimer();
}
function showtimer() {
var now = new Date();
var remain = end – now; // Get The Difference Between Current and entered date time
if(remain < 0)
{
clearInterval(timer);
// document.getElementById("timer_value").innerHTML = 'Reached!';
document.getElementById("timer_days").innerHTML = 0 ;
document.getElementById("timer_hrs").innerHTML = 0;
document.getElementById("timer_min").innerHTML = 0 ;
document.getElementById("timer_secs").innerHTML = 0 ;
alert("Reached")
return;
}
var days = Math.floor(remain / day); // Get Remaining Days
var hours = Math.floor((remain % day) / hour); // Get Remaining Hours
var minutes = Math.floor((remain % hour) / minute); // Get Remaining Min
var seconds = Math.floor((remain % minute) / second); // Get Remaining Sec
document.getElementById("timer_days").innerHTML = days ;
document.getElementById("timer_hrs").innerHTML = hours;
document.getElementById("timer_min").innerHTML = minutes ;
document.getElementById("timer_secs").innerHTML = seconds ;
timer = setInterval(showtimer, 1000); // Display Timer In Every 1 Sec
}
Joken Villanueva
March 1, 2018hello sir. Thanks for sharing this code.
Akshay Singh
April 13, 2018how reset the cache for next case or i am using it for online quiz Please Help
Akshay Singh
April 13, 2018how reset the cache for next case or i am using it for online quiz Please Help
Manish
January 12, 2019I am not sure where to paste the “cache” script.. I tried putting in html section, but it coming as text. I don’t have an option to add a php function, can I get the cache code in JV script instead
7M
August 8, 2019Great article.
velu
September 16, 2019how to display a link after the timer expires
Shuvika
February 27, 2020i can find the countdown code without refreshing the page only on your site. IT is very useful i just change the code for setting timer only for 1 minute. Thank you fro the code.
Shuvika
February 27, 2020i can find the countdown code without refreshing the page only on your site. IT is very useful i just change the code for setting timer only for 1 minute. Thank you fro the code. Very Good knowledge.
Lokesh babu
March 11, 2020Hi i need to implement a javascript quiz with count down timer in which there is a time set for each question? Can u please help on this?
Bharath
June 11, 2020Hi Navaneeth, is it possible to cache the time when refreshed and run from cache .. for example, if someone refreshes at 1:32, the page should start at 1:32 … is that possible?
navaneeth
July 23, 2020we need to use the local storage to handle that