Function calling itself not working (infinite loop, Javascript)

I try to wait and then get a message when all the images in the array have finished loading (using .complete), for the answer here . Thus, I set up an infinite loop, as shown below. however, when I run this, I get an error that checkForAllImagesLoaded () is not defined. This code is run through the bookmarklet, and as such, it terminates in an anonymous function construction (as shown below). If I redefine my function and variable outside of this construct, it works. But this is a bad way to write a bookmarklet. How can I fix this, so it will recognize the function after setTimeout?

(function() { //var images = array of images that have started loading function checkForAllImagesLoaded(){ for (var i = 0; i < images.length; i++) { if (!images[i].complete) { setTimeout('checkForAllImagesLoaded()', 20); return; } } } checkForAllImagesLoaded(); })(); 
+7
javascript function callback definition anonymous-function
source share
3 answers

Remove the function call and pull out the quotation marks. If you do not put quotation marks, setTimeout gets a direct link to a function that it can call later. However, if inside a line such as "checkForAllImagesLoaded" or "checkForAllImagesLoaded()" , then it will execute the passed code when the timeout occurs.

At this time, the global object (window) will search for checkForAllImagesLoaded , but it is not defined there, so the reason you get the undefined error.

Your code is wrapped in an anonymous self-starting function, and checkForAllImagesLoaded does not exist outside it. Therefore, pass a direct reference to the function in the setTimeout call, not the string.

 setTimeout(checkForAllImagesLoaded, 20); 

setTimeout can be called using a function (and optional arguments) or a string containing JavaScript code:

 var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); var timeoutID = window.setTimeout(code, delay); 
+7
source share

Remove () in the setimeout call.

setTimeout('checkForAllImagesLoaded', 20);

+1
source share

Using your code, you set the number of timeouts per call. You should simply set a timeout once per checkForAllImagesLoaded() and possibly increase the wait period (20 milliseconds is just too fast). For example.

 function checkForAllImagesLoaded() { var allComplete=true; var i=0; while (i<images.length && allComplete) { allComplete=images[i++].complete; } if (!allComplete) { // Any incomplete images? setTimeout('checkForAllImagesLoaded()',1000); // Wait a second! } } 
+1
source share

All Articles