I am trying to display several count down timers on same page. now as far as i know there are 2 ways of doing it without using jquery plugins or some other scripts (if you know of a good one please let me know)
-
starting 1 sec
setIntervaland a global variable that will contain milliseconds and then just reduce -1000 every interval. -
creating a function that reduce 1 sec from a global variable and then at the bottom of that function setting a
setTimeoutof 1 sec that will run that functions so basically recursion every 1 sec.
My question is which of the 2 options will work better and/or faster?
here is demonstrative code for both:
setInterval:
var amount_of_seconds_left = 46800000;
setInterval(function(){
if(amount_of_seconds_left > 1000){
amount_of_seconds_left -= 1000;
}
},1000);
setTimeout:
var amount_of_seconds_left = 46800000;
function startTime(){
if(amount_of_seconds_left > 1000){
amount_of_seconds_left -= 1000;
t=setTimeout(function(){startTime()},1000);
}
}
Both ways could work but i was wondering performance wise which is better and is performance is even an issue with this ?
setIntervalandsetTimeoutdon’t start after 1000ms e.g. if another script is running, so both can cause delays. It would be better to use thesetIntervallto call the display update only and use the theDateobject to calculate the exactly remaining time. E.g. after the browser was busy the timer shows the correct time after the next update.Here an example:
HTML:
javascript: