首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript等待直到最后一个事件在回调中触发,然后再继续

Javascript等待直到最后一个事件在回调中触发,然后再继续
EN

Stack Overflow用户
提问于 2015-07-05 18:20:06
回答 1查看 589关注 0票数 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秒,然后记录‘这里’。如果另一个“完全”触发,我想摆脱以前的计时器,并启动一个新的。基本上是等到所有的“完成”被发射…我需要帮助修复我的间隔逻辑..。

EN

Stack Overflow用户

回答已采纳

发布于 2015-07-05 18:33:09

您必须在函数作用域之外声明timerinterval,否则它将在该作用域中声明一个新的回调,而您的clearInterval无法清除以前的间隔回调。

编辑:多亏了stdob--,现在将外部变量更改为坚持eventTarget,因此不再需要在注册事件之前声明variables

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
    }
});
票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31233538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档