Firefox XPCOM setTimeout problem
I am writing a simple firefox extensions which 开发者_开发百科crawls a bunch of urls and extracts certain fields (all urls that are crawled will be loaded in the user's tab).
The problem I am facing is in the part actually visits the URL and loads the page. I want each page to be loaded at a fixed timer period. eg, Each site to be visited every 5 seconds.
I tried the two methods listed here http://groups.google.com/group/mozilla.dev.extensions/browse_thread/thread/de47c3949542b759 but to no avail. Using both Components.classes["@mozilla.org/appshell/appShellService;1"] and also nsITimer. The while loops executes immediately and the pages are loaded later (after about 5 seconds in quick succession)
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();
}
How do I implement the timer function that calls gotoURL every 5 seconds correctly? Thanks!
Well, setTimeout
is executed asynchronously. The loop does not wait until the function is called. You have to change the strategy (if I understood you correctly).
For example you could trigger the next setTimeout
after you extracted the information:
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();
}
And yes, it is better to use nsITimer
.
精彩评论