我正在写一个简单的firefox扩展,它抓取一堆urls并提取某些字段(抓取的所有urls都将加载到用户的标签中)。
我面临的问题是部分实际访问URL并加载页面。我希望每个页面加载在一个固定的计时器周期。例如,每个站点每5秒访问一次。
我尝试了这里列出的两种方法http://groups.google.com/group/mozilla.dev.extensions/browse_thread/thread/de47c3949542b759,但都没有用。同时使用Components.classes"@mozilla.org/appshell/appShellService;1“和nsITimer。while循环立即执行,稍后加载页面(大约连续5秒后)
function startCrawl()
{
while(urlq.length>0)
{
var currentUrl = urlq.shift();
urlhash[currentUrl]=1;
if(currentUrl!=undefined)
{
setTimeout(gotoURL,5000,currentUrl);
}
}
start=0;
alert('crawl stopped');
for(var k in foundData)
{
alert('found: ' + k);
}
}
function gotoURL(gUrl)
{
mainWindow.content.wrappedJSObject.location=gUrl;
extractContent();
}如何正确实现每5秒调用一次gotoURL的定时器函数?谢谢!
发布于 2011-04-26 01:34:47
嗯,setTimeout是异步执行的。在调用函数之前,循环不会等待。你必须改变策略(如果我没理解错的话)。
例如,您可以在提取信息后触发下一个setTimeout:
function startCrawl() {
function next() {
var currentUrl = urlq.shift();
if(currentUrl) {
setTimeout(gotoURL,5000,currentUrl, next);
}
}
next();
}
function gotoURL(gUrl, next) {
mainWindow.content.wrappedJSObject.location=gUrl;
extractContent();
next();
}是的,最好使用nsITimer。
https://stackoverflow.com/questions/5781056
复制相似问题