Calvin
Calvin

Reputation: 309

Javascript settimeout on recursive function?

function theFunction(a){
    var newNum = a+1;
    var iframe = document.createElement("iframe");
    var currURL = urlArray[a];
    iframe.src = currURL;
    iframe.frameBorder = "0";
    iframe.height = "0";
    iframe.width = "0";

iframe.onload = function(){
    document.getElementById('number').innerHTML = a;
};
    var arrayLength = someArray.length;

    if(a != arrayLength){
     theFunction(newNum);
     }
}

This is my basic function that is recursive through an array. Anyways, sometimes as it goes through (during the //do nothing part). It will get stuck, and I want it to timeout after say 2 seconds AND move onto the next one. Is this possible to do, or will I just have to completely stop the function?

EDIT: Set timeout might not be what I am looking for, but some way to just stop the function and move to the next one.

EDIT 2: Added more to the code

Upvotes: 3

Views: 380

Answers (2)

anson
anson

Reputation: 4164

You could "try" to use iframe.contentDocument.readyState, but I say "try" with little confidence because with my tests it always came out to the "complete" state, but possibly when you run in to some pages that take awhile to load they may stay in some of the previous states.

For more information on this and the different states view this

http://msdn.microsoft.com/en-us/library/ms534358%28v=vs.85%29.aspx

Upvotes: 0

Chris
Chris

Reputation: 7278

Hmmm. Do you know exactly what's happening when it get "stuck"? Because if "stuck" means hitting a loop or some other error then setTimeout won't help you. In my experience, code set to execute with setTimeout will happen when the given delay has passed or when other code has stopped executing, whichever happens LAST. In other words, I don't think you can interrupt currently running code with a setTimeout, which seems to be what you're asking.

I know that's sort of a non-answer; I suggest nailing down the nature of the stuckness instead.

Upvotes: 1

Related Questions