1
function timer(time,max) {
   if(time-1>=0) {
     --time;
       $("#timer2").html(Math.ceil(time/100));
          pix = Math.round((time/max)*100);
   document.getElementById('timer').style.width = pix+"%";
  setTimeout("timer("+time+","+max+")",10);
  }
 }

那是Javascript。

 You have <font style='color: #ff0' id='timer2'><?PHP echo $time; ?></font> seconds left until you can skill again<br>
<div style='background-color: black; width: 100px;'>
    <div style='background-color: #ffd700; text-align: center; width: 100%' id='timer'>&nbsp;
    </div>
</div>
<script>
    timer(<?PHP echo $time*100; ?>,<?PHP echo $time*100; ?>);
</script>

基本上,时间可以是 X 秒。计时器每 10 毫秒运行一次,因此条形图看起来很平滑。问题是,当您离开该选项卡时,它会停止移动。有没有办法治愈这段代码来做到这一点?

谢谢!

4

2 回答 2

1

In modern browsers, timeouts and intervals are throttled when the tab is inactive, so your timer function is only firing once per second instead of 100 times per second while the tab is inactive.

要解决这个问题,您需要存储动画开始的时间Date.now()(自开始以来经过的时间量。

示例(jsfiddle

timer = function(max) {
    if (timer.start === undefined) timer.start = Date.now();
    if (timer.max === undefined) timer.max = max;

    var max = timer.max,
        elapsed = Date.now() - timer.start,
        left = Math.max(max - elapsed, 0),
        pctLeft = Math.min(left/max, 1);

    $('#timer2').html(Math.ceil(left/1000));
    $('#timer').css('width', pctLeft * 100 + '%');

    if (left > 0) setTimeout(timer, 30);
    else timer.start = timer.max = undefined;
 }

timer(5000);
​
于 2012-12-11T18:53:05.717 回答
1

如果您已经在使用 jQuery,请查看jQuery 计时器插件。

于 2012-12-11T18:41:05.103 回答