如何在手机锁定时运行计时器?

时间:2012-08-04 05:29:25

标签: javascript android

我需要JavaScript的帮助。我正在使用此代码来获取程序的执行时间:

if(seconds == sec){alert(sec);}

function countdown(element) {
    interval = setInterval(function() {
        var el = document.getElementById(element);    
        if(seconds == 0) {
          //alert(seconds);
          if(minutes == 0) {
            el.innerHTML = "00 : 00"; 
            alert("Sorry, you have exceeded our booking time and your order has been cancelled. We are afraid you have to start over!",null,'');
            clearInterval(interval);
            ajax_load_image();
            window.location.href='movies.html';
            return;
          } else {
            minutes--;
            seconds = 60;
          }
        }
        if(minutes > 0) {     
          var minute_text = minutes+(minutes > 1 ? ' ' : ' ');
        } else {
          var minute_text = '0';
        }
        if(minute_text<0)
        {
          $('#countdown').css('color','red');
        }
        var second_text =seconds > 1 ? '' : '';
        if(minute_text=='')
        {
          el.innerHTML ='0 : '+seconds;
        }
        else
        {
          if(seconds<10)
          {
            seconds='0'+seconds;
          }  
          el.innerHTML = '0'+minute_text + ' : ' + seconds + ' ' + second_text + ' Min';
        }
        seconds--;
    }, 1000);
}

当我锁定手机时,计时器会自动停止。当我锁定手机时,我该怎么做才能运行计时器。帮助我。

1 个答案:

答案 0 :(得分:0)

如果您关心实际通过的时间,请不要依赖setInterval() - 将开始时间与当前时间进行比较。

var startTime = new Date();

setInterval(function() {
   // you might need to call .getTime() here - this works in Chrome,
   // but that might be implementation-dependent
   var seconds = ((new Date()) - startTime) / 1000;

   // etc
});

我不知道这在移动环境中是如何工作的,但是当你解锁并且setInterval()再次运行时它会正常超时。