浏览器是否跟踪活动计时器 ID?
-
26-09-2019 - |
题
浏览器是否跟踪活动 setInterval
和 setTimeout
身份证?或者这完全取决于开发人员来跟踪?
如果它确实跟踪它们,是否可以通过 BOM 访问?
解决方案
由开发人员来跟踪。您可以通过使用 setTimeout/setInterval 函数的返回值并将该值传递给clearTimeout/clearInterval 函数来完成此操作 - 如此处其他答案中所述。
这似乎是因为每个浏览器都会以自己的方式实现跟踪间隔。
来自 w3.org/TR/2009/WD-html5-20090212/no.html(草案,但 w3schools 和 http://w3.org/TR/Window 以几乎相同的方式解释它) - setTimeout 和 setInterval 返回一个 long 值,而clearTimeout/clearInterval 接受一个 long 值来查找和取消
其他提示
可以添加这样的全局定时器通过重写setTimeout
/ seInterval
功能跟踪。作为奖励,您可以轻松地将定时器设定或弹出添加代码,跟踪现场定时器或弹出计时器,等等...
例如:
timers = {}; // pending timers will be in this variable
originalSetTimeout = window.setTimeout;
// override `setTimeout` with a function that keeps track of all timers
window.setTimeout = function(fu, t) {
var id = originalSetTimeout(function() {
console.log(id+" has timed out");
delete timers[id]; // do not track popped timers
fu();
}, t);
// track this timer in the `timers` variable
timers[id] = {id:id, setAt: new Date(), timeout: t};
console.log(id+" has been set to pop in "+t+"ms");
}
// from this point onward all uses of setTimeout will be tracked, logged to console and pending timers will be kept in the global variable "timers".
这您可能会感兴趣,如果你是好奇如何定时器由它的窗口“记住”。
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title>Timer </title>
</head>
<body>
<h1>Timers</h1>
<script>
if(!window.timers){
var timers= [], i= 0;
while(i<5){
timers.push(setInterval(function(){
if(confirm(timers.join('\n')+'\nRemove a timer?')){
clearInterval(timers.shift());
}
},
i*1000+1000));
++i;
}
}
</script>
</body>
</html>
更新:
这个问题有两个方面。
- 浏览器是否跟踪计时器 ID?
- 他们是否可以访问
我只能假设#1(以及后来的#2)OP 的意思是一般意义上的“它们是否被跟踪”,因为作为开发人员,他/她希望控制它们。
简而言之,是的,它们被跟踪了(正如@s_hewitt 指出的那样, long
浏览器的值),并且开发人员可以通过在设置时维护对计时器的引用来管理它们。
作为开发人员,您可以控制(例如通过调用 (清除间隔(handleRef), , 或者 清除超时(handleRef))
但是没有默认值 window.timers
或类似的集合,为您提供现有计时器的列表 - 如果您觉得需要,您将需要自己维护该列表。
function startPolling(delay){
pollHandle = setInterval(doThis, delay);
}
function stopPolling(){
clearInterval(pollHandle);
}
function doThisIn30minUnlessStopped(){
timerHandle = setTimeout(doThisThing, 1800000);
}
function stop30minTimer(){
clearTimeout(timerHandle);
}
您只需创建一个对计时器的变量引用,并且如果/需要时,按名称清除它。
当您加载另一个页面时,所有计时器都会被浏览器自动清除,因此您不需要维护句柄,并清除它们,除非您需要/想要。
看看下面的脚本中,浏览器可以记住每个的setTimeout迭代
的idfor (i = 1; i <= d; i++) {
(function(j) {
var delay = j/d;
t[j] = setTimeout(function() {
elem.style.top = j+"px";
},delay);
})(i);
}
可以通过访问它们
for (i in t) {
alert(t[i]);
}