这几乎是一个基本的Javascript问题,尽管它涉及到一些Chrome扩展API。
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秒,然后记录‘这里’。如果另一个“完全”触发,我想摆脱以前的计时器,并启动一个新的。基本上是等到所有的“完成”被发射…我需要帮助修复我的间隔逻辑..。
发布于 2015-07-05 18:33:09
您必须在函数作用域之外声明timer和interval,否则它将在该作用域中声明一个新的回调,而您的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.
}
});因此,现在每个interval和timer都指向同一个目标。
或者如果你不关心每一秒发生什么,为什么不使用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);
}
});https://stackoverflow.com/questions/31233538
复制相似问题