开发者

Adding a timer to an event listener in JavaScript

I'm having a little bit of trouble managing the load of sites in a Firefox extension.

I'm using JavaScript and developing a Firefox extension to search a string in a list of websites of my own, to look for bad words. The problem is that I am searching the list one by one. That means, I am loading a webpage and I add an event listener to DOMContentLoaded; when the DOM loads a function is called to search for the string. But, if the page does not load (A network issue for example) the function is never called.

Is there a way to set a timer to an event listener? If the event is not triggered in 5 seconds then do something. Or if there is another way to do that please advice! I minimized the code a lot but i think you can get the idea here.

function main_(){
            //do some stuff here and if needed call to open a new page
            waitForDOM();
}

function waitForDOM(){
            //if 开发者_JS百科the list of pages is grather than 0 then
    //add the new tab here and create the event listener
    gBrowser.addEventListener('DOMContentLoaded',pageLoaded,true);
 }

function pageLoaded(aEvent) {
        //do the search here and calls the function waitForDOM to load a new page and a event listener
    waitForDOM();
}


I don't know anything about coding Firefox extensions, but in a general sense you can certainly set a timer to do something if your event handler isn't called within a certain time. Something like this:

var eventTriggeredFlag = false;

function waitForDOM(){
  gBrowser.addEventListener('DOMContentLoaded',pageLoaded,true);
  setTimeout(function(){
               if (!eventTriggeredFlag) {
                  // time's up without the event: do something
               }
             }, 5000);
}

function pageLoaded(aEvent) {
  eventTriggeredFlag = true;
  // whatever else you want to do here...
}

If you need to keep track of multiple events with separate timers you'd obviously have to make that more complicated, perhaps with some closures or an array of events or something.


It is better to add a progress listener instead of using DOMContentLoaded. The method onStateChange of your progress listener will always be called with STATE_STOP and STATE_IS_WINDOW flags when the page finishes loading - regardless of whether there is an error or not. You can call Components.isSuccessCode(aStatus) to see whether the page loaded successfully (note that this will only report network errors, HTTP errors like 404 will still count as success).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜