2015-07-05 66 views
0

这几乎是一个基本的Javascript问题,即使它涉及一些Chrome扩展API。Javascript正在等待最后一个事件发生在回调之前继续

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    if (changeInfo.status == 'complete') { 
     //complete may fire multiple times per page update 
     var timer = 0, interval; 
     console.log(changeInfo.status); 
     clearInterval(interval); 
     interval = setInterval(function() { 
      if (timer == 5) { 
       console.log('here'); 
       clearInterval(interval); 
      } 
      timer++; 
     }, 1000); 
    } 
}); 

我认为我现在所有的脚本都会延迟一切。我希望它做的是每次发生“完整”状态时,我想检查5秒钟,然后在此处登录。如果另一个'完成'激发,我想摆脱以前的计时器并开始一个新的计时器。基本上等到所有的'完成'被解雇......我需要帮助修复我的间隔逻辑...

回答

2

你必须声明你的timerinterval超出函数范围,否则它会在该范围内声明一个新的,并且您的clearInterval无法清除之前的区间回调。

编辑:感谢stdob--,现在改变了外面的变量以保持eventTarget,所以在注册事件之前不需要声明variables

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    if (changeInfo.status == 'complete') { 
     //complete may fire multiple times per page update 
     console.log(changeInfo.status); 
     // Clear prev counter, if exist. 
     if (this.interval != null) { 
      clearInterval(this.interval); 
     } 
     // init timer 
     this.timer = 0;     
     this.interval = setInterval(function() { 
      if (this.timer == 5) { 
       console.log('here'); 
       clearInterval(this.interval); 
       this.interval = null; 
      } 
      this.timer++; 
     }.bind(this), 1000); // Important to .bind(this) so that context will remain consistent. 
    } 
}); 

所以现在每intervaltimer指向同一个目标。

或者,如果你不关心每一秒发生了什么,为什么不使用setTimeout

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    if (changeInfo.status == 'complete') { 
     console.log(changeInfo.status); 
     if (this.timeout != null) { 
      clearTimeout(this.timeout); 
     } 

     this.timeout = setTimeout(function() { 
      console.log("here"); 
      this.timeout = null; 
     }.bind(this), 5000); 
    } 
}); 
+1

最佳方式使用静态变量:this.interval = setInterval的(...) –

+0

@stdob但随后如果他使用setInterval方式,他需要将间隔回调绑定到'this',对吧? – fuyushimoya

+0

为什么不如果他不想进入间隔时间?有些像这样: 'if(typeof this.interval =='undefined')this.interval = null;'@fuyushimoya –

相关问题