在超时时从H-“小时”切换到M-“分钟”而不刷新

时间:2011-08-28 23:27:03

标签: javascript

我制作了这个计时器,每小时显示H-“剩余小时数”,每分钟显示M-“剩余时间”,秒数相同,具体取决于时间戳值。

您是否看到我的脚本中需要改进的内容以及如何在不刷新页面的情况下从小时计时器切换到分钟计时器,从分钟计时器切换到秒计时器:

    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 );         

   }; 

1 个答案:

答案 0 :(得分:1)

您只需要一个计时器并将时钟设置为适当的值。

setInterval 在所需的时间间隔后尽快运行 - 如果系统繁忙,它将运行一段时间并缓慢漂移。最好使用 setTimeout - 估计下一个纪元的时间,并在下一个整个时间间隔后约20ms再次运行。