SetInterval是否可以阻塞页面中的其他脚本?JavaScript的setInterval块可以执行线程吗?
我正在开发一个项目,将Gmail相关书签转换为Google Chrome扩展程序。小书签使用gmail greasemonkey API与gmail页面进行交互。 API的JavaScript对象是要加载的Gmail页面的最后部分之一,并通过XMLHttpRequest加载到页面中。由于我需要访问此对象,并且全局JavaScript变量对扩展内容脚本隐藏,因此我在gmail页面中注入了一个脚本,用于轮询变量的定义,然后访问它。我正在使用setInterval函数进行轮询。这大约80%的时间工作。其余时间轮询功能保持轮询,直到达到我设置的限制,并且从未在页面中定义greasemonkey API对象。
注入脚本示例:
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是单线程的......如果这就是你的意思。 – 2012-08-15 23:09:24