JavaScript的setInterval块可以执行线程吗? [英] Can JavaScript's setInterval block thread execution?

查看:193
本文介绍了JavaScript的setInterval块可以执行线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SetInterval是否会导致页面中的其他脚本阻塞?



我正在开发一个项目,将Gmail相关的书签转换为Google Chrome扩展程序。小书签使用gmail greasemonkey API与gmail页面进行交互。 API的JavaScript对象是要加载的Gmail页面的最后部分之一,并通过XMLHttpRequest加载到页面中。由于我需要访问此对象,并且全局JavaScript变量对扩展内容脚本隐藏,因此我在gmail页面中注入了一个脚本,用于轮询变量的定义,然后访问它。我正在使用setInterval函数进行轮询。这大约80%的时间工作。其余时间轮询功能保持轮询直到达到我设置的限制,并且从未在页面中定义greasemonkey API对象。



注入脚本示例:

  var attemptCount = 0; 

var tryLoad = function(callback){

if(typeof(gmonkey)!=undefined){
clearInterval(intervalId); //取消注册此函数以进行间隔执行。
gmonkey.load('1.0',function(gmail){
self.gmail = gmail;
if(callback){callback();}
});
}
else {
attemptCount ++;
console.log(Gmonkey not yet loaded:+ attemptCount);
if(attemptCount> 30){
console.log(在三十秒后无法在gmail页面中启动Gmonkey。中止);
clearInterval(intervalId); //取消注册此函数以进行间隔执行。
};
}
};

var intervalId = setInterval(function(){attemptLoad(callback);},1000);


解决方案

Javascript是单线程的这里没有提到)。这意味着只要正常的JavaScript执行线程正在运行,您的 setInterval()定时器将不会运行,直到执行正常的JavaScript线程完成为止。



同样,如果你的 setInterval()处理程序正在执行,那么在你的 setInterval()处理程序完成它的当前调用。



所以,只要你的 setInterval()处理程序不会卡住并永久运行,它不会阻止其他事情最终运行。它可能会稍微延迟它们,但是只要当前 setInterval()线程完成,它们仍然会运行。



在内部,JavaScript引擎使用一个队列。当某事想要运行时(比如事件处理程序或 setInterval()回调),并且某个东西已经在运行时,它会将一个事件插入到队列中。当前的JavaScript线程完成执行时,JS引擎会检查事件队列,如果有事件发生,它会在那里选择最旧的事件并调用其事件处理程序。



这里是关于Javascript事件系统如何工作的其他参考资料:如何在后台处理AJAX响应?



是否调用Javascript方法线程安全或同步?



我需要关注异步Javascript的竞争条件吗?


Can setInterval result in other scripts in the page blocking?

I'm working on a project to convert a Gmail related bookmarklet into a Google Chrome extension. The bookmarklet uses the gmail greasemonkey API to interact with the gmail page. The JavaScript object for the API is one of the last parts of the Gmail page to load and is loaded into the page via XMLHttpRequest. Since I need access to this object, and global JavaScript variables are hidden from extension content scripts, I inject a script into the gmail page that polls for the variable's definition and then accesses it. I'm doing the polling using the setInterval function. This works about 80% of the time. The rest of the time the polling function keeps polling until reaching a limit I set and the greasemonkey API object is never defined in the page.

Injected script sample:

    var attemptCount = 0;

    var attemptLoad = function(callback) {

        if (typeof(gmonkey) != "undefined"){
            clearInterval(intervalId);  // unregister this function for interval execution.
            gmonkey.load('1.0', function (gmail) {
                self.gmail = gmail;
                if (callback) { callback(); }
            });
        }
        else {
            attemptCount ++;  
            console.log("Gmonkey not yet loaded: " + attemptCount );
            if (attemptCount > 30) {
                console.log("Could not fing Gmonkey in the gmail page after thirty seconds.  Aborting");
                clearInterval(intervalId);  // unregister this function for interval execution.
            };
        }
    };

    var intervalId = setInterval(function(){attemptLoad(callback);}, 1000);

解决方案

Javascript is single threaded (except for web workers which we aren't talking about here). That means that as long as the regular javascript thread of execution is running, your setInterval() timer will not run until the regular javascript thread of execution is done.

Likewise, if your setInterval() handler is executing, no other javascript event handlers will fire until your setInterval() handler finishes executing it's current invocation.

So, as long as your setInterval() handler doesn't get stuck and run forever, it won't block other things from eventually running. It might delay them slightly, but they will still run as soon as the current setInterval() thread finishes.

Internally, the javascript engine uses a queue. When something wants to run (like an event handler or a setInterval() callback) and something is already running, it inserts an event into the queue. When the current javascript thread finishes execution, the JS engine checks the event queue and if there's something there, it picks the oldest event there and calls its event handler.

Here are a few other references on how the Javascript event system works:

How does JavaScript handle AJAX responses in the background?

Are calls to Javascript methods thread-safe or synchronized?

Do I need to be concerned with race conditions with asynchronous Javascript?

这篇关于JavaScript的setInterval块可以执行线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆