2015-07-05 64 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 –

相關問題