一、问题现象
一个H5项目中,需要在页面中显示倒计时信息。然后发现在iphone、ipad中,锁屏一段时间后再打开,锁屏那段时间并没有倒计时。代码如下:
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function () {
method.call(context);
}, 1000);
}
function timeHandler() {
var that = this;
$.each(config.arrRemainTime, function (key, item) {
if (item.time > 0) {
item.time = item.time - 1;
//显示倒计时
that.throttle(that.timeHandler, that);
}
});
}
throttle(this.timeHandler, this);
二、原因分析
google后,找到一篇文章:http://stackoverflow.com/questions/7047989/javascript-stops-as-i-lock-iphone-can-it-still-run
原因如下:
You cannot continue to run javascript while the iPhone is sleeping using setTimeout()
, however.When the phone is put to sleep, Safari will kill any running javascript processes using setTimeout()
. Check out this answer here for some reasons why this is done.