18

浏览器是否跟踪活动setIntervalsetTimeoutID?还是这完全取决于开发人员来跟踪?

如果它确实跟踪它们,是否可以通过 BOM 访问?

4

5 回答 5

4

由开发人员来跟踪。您可以通过使用 setTimeout/setInterval 函数的返回值并将该值传递给 clearTimeout/clearInterval 函数来执行此操作 - 如此处其他答案中所述。

这似乎是因为每个浏览器都会以自己的方式实现跟踪间隔。

来自 w3.org/TR/2009/WD-html5-20090212/no.html (草稿,但 w3schools 和http://w3.org/TR/Window的解释方式几乎相同) - setTimeout 和 setInterval 返回很长并且 clearTimeout/clearInterval 接受一个 long 来查找和取消

于 2010-05-12T15:48:14.533 回答
4

您可以通过覆盖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".
于 2012-10-28T13:23:25.607 回答
1

如果您对计时器如何被其窗口“记住”感到好奇,这可能会让您感兴趣。

<!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> 
于 2010-05-11T23:59:46.073 回答
0

更新:

这个问题有2个方面。

  1. 浏览器是否跟踪计时器 ID?
  2. 他们是否可以访问

对于#1(以及后来的#2),我只能假设 OP 在一般意义上意味着“他们是否被跟踪”,因为作为开发人员,他/她希望控制它们。

简而言之,是的,它们被跟踪(正如@s_hewitt 所指出的,作为long浏览器的值),并且开发人员可以通过在设置时维护对计时器的引用来管理它们。

作为开发人员,您可以通过调用(clearInterval(handleRef)clearTimeout(handleRef))来控制(例如停止)它们

但是,没有默认window.timers或类似的集合可以为您提供现有计时器的列表 - 如果您觉得需要,您需要自己维护它。

function startPolling(delay){
  pollHandle = setInterval(doThis, delay);
}
function stopPolling(){
  clearInterval(pollHandle);
}

function doThisIn30minUnlessStopped(){
  timerHandle = setTimeout(doThisThing, 1800000);
}
function stop30minTimer(){
  clearTimeout(timerHandle);
}    

您只需要创建一个对您的计时器的变量引用,并在需要时按名称清除它。

当您加载另一个页面时,浏览器会自动清除所有计时器,因此您无需维护句柄,并清除它们,除非您需要/想要。

于 2010-05-11T23:13:39.483 回答
0

看下面的脚本,浏览器可以记住每次 setTimeout 迭代的 id

for (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]);  
 }
于 2010-05-12T15:41:10.323 回答