从H "小时"M产生绯闻,minutes"在没有刷新的计时器中

Switch from the H-"hours" to M-"minutes" in a timer whitout refreshing

本文关键字:quot 刷新 计时器 minutes 绯闻 小时      更新时间:2023-09-26

我制作了这个计时器,它每小时显示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 );         
   }; 

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

setInterval在所需的时间间隔后尽快运行-如果系统繁忙,它将运行得稍微晚一些并慢慢漂移。最好使用setTimeout -估计到下一个epoch的时间,并在下一个整个间隔后大约20ms再次运行它。