Skip to content Skip to sidebar Skip to footer

Loops In Javascript / Monitoring Objects For Updates

I have an iframe. I want to create a loop in Javascript that monitors the iframe's URL. So what I want is something like this: while(1){ if(iframe.src == 'foo'){ iframe

Solution 1:

If you have an infinite loop you have to stop it manually using break:

while (1) {
    if(...) {
        ...
        break; //exit loop
    }
}

Is this what you wanted to ask? Feel free to ask any further question.

Edit:

The solution I would choose is creating an own event to listen for and a function to trigger the event if needed:

var iframeSrcChangeEvt = new Event("iframeSrcChanged"); //create event
document.querySelector("iframe").addEventListener("iframeSrcChanged",function() { //add event listener to the iframe
    this.src = "bar"; //change src as you need it
    this.removeEventListener("iframeSrcChanged"); //remove listener if fired
    clearInterval(monitorIframe); //stop monitoring the iframe
});

var monitorIframe = setInterval(function() { //set an interval to monitor the iframe
    var iframe = document.querySelector("iframe");
    if(iframe.src == "foo") {
        iframe.dispatchEvent(iframeSrcCHangeEvt); //fire event
    }
 },500);

I think this solution is better because you are able to add more than one iframe to monitor if you adapt that code.


Post a Comment for "Loops In Javascript / Monitoring Objects For Updates"