javascript中是否有任何类似setInterval()的方法,当用户离开标签时会停止并在用户再次进入标签时恢复?
答案 0 :(得分:1)
您可以使用Visibility API创建自己的API,以检测标签何时变为可见或隐藏,并调用本机setInterval
和clearInterval
。
var mySetInterval, myClearInterval;
(function() {
var data = Object.create(null),
id = 0;
mySetInterval = function mySetInterval(func, time) {
data[id] = {
nativeID: setInterval(func, time),
func: func,
time: time
};
return id++;
};
myClearInterval = function myClearInterval(id) {
if(data[id]) {
clearInterval(data[id].nativeID);
delete data[id];
}
};
document.addEventListener('visibilitychange', function() {
if(document.visibilityState == 'visible')
for(var id in data)
data[id].nativeID = setInterval(data[id].func, data[id].time);
else
for(var id in data)
clearInterval(data[id].nativeID);
});
})();
var mySetInterval, myClearInterval;
(function() {
var data = Object.create(null),
id = 0;
mySetInterval = function mySetInterval(func, time) {
data[id] = {
nativeID: setInterval(func, time),
func: func,
time: time
};
return id++;
};
myClearInterval = function myClearInterval(id) {
if(data[id]) {
clearInterval(data[id].nativeID);
delete data[id];
}
};
document.addEventListener('visibilitychange', function() {
if(document.visibilityState == 'visible')
for(var id in data)
data[id].nativeID = setInterval(data[id].func, data[id].time);
else
for(var id in data)
clearInterval(data[id].nativeID);
});
})();
var log = document.getElementById('log'),
timer;
document.getElementById('start').onclick = function() {
var num = 0;
myClearInterval(timer);
timer = mySetInterval(function(){
log.innerHTML = num++;
}, 1e3);
};

<input id="start" type="button" value="Start" />
<span id="log"></span>
&#13;
请注意,上述API不应与原生API混合使用,例如:不要尝试使用mySetInterval
创建并使用clearInterval
清除。因此,mySetInterval
返回的ID故意与本地ID不同。