Switch from the H-"hours" to M-"minutes" in a timer whitout refreshing
I made this timer which display H-"hours remaining" every hours, M-"minutes remaining" every minutes, same for seconds, depending on a timestamp value.
Do you see things to improve in my script and how switch from the hours timer to the minute one and from the minute one to the seconds one without refreshing the page :
window.onload = function() {
var actual_timestamp = Math.round((new Date()).getTime() / 1000);
var time_remaining=<?php echo $vote_time_limit ?> - actual_timestamp;
var spanElt = document.getElementById('timer');
var h,m,s;
setInterval( function() {
//If time_remaining is between 24 and 1h, it decreases every hours
if(time_remaining<=86400 && time_remaining>=3600){
h=Math.floor( time_remaining / 3600 % 24);
spanElt.innerHTML="H-"+h--;
time_remaining--;
}
} , 3600000 );
setInterval( function() {
//If time_remaining is between 开发者_如何转开发1h and 1min, it decreases every minutes
if(time_remaining<3600 && time_remaining>=60){
m=Math.floor( time_remaining / 60 % 60);
spanElt.innerHTML="M-"+m--;
time_remaining--;
}
} , 60000 );
setInterval( function() {
//If it is between 60sec and 0sec, it decreases every seconds
if(time_remaining<60 && time_remaining>0){
s=Math.floor( time_remaining % 60);
spanElt.innerHTML="S-"+s--;
time_remaining--;
//If time_remaining =0, it takes the value of the cycle time
}else if(time_remaining==0){
time_remaining=86400; //24h
}
} , 1000 );
};
You only need one timer and set the clock to the appropriate value.
setInterval runs as soon as it can after the required interval - if the system is busy it will run a little late and slowly drift. Better to use setTimeout—estimate the time to the next epoch and run it again about 20ms after the next whole interval.
精彩评论