Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function calling itself not working (infinite loop, Javascript)

I'm trying to wait and then get a message when all images in an array have completed loading (using .complete), per the answer here. As such I set up an infinite loop like the below. however, when I run this I get an error that checkForAllImagesLoaded() is not defined. This code is being run through a bookmarklet, and as such it's all wrapped up in an anonymous function construct (as below). If I re-define my function and variable outside of that construct, it works. But that seems to be a poor way to write a bookmarklet. How can I fix this so it will still recognize the function after the 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();

})();
like image 485
Red Collar Avatar asked Jun 30 '10 01:06

Red Collar


People also ask

What happens for infinite loop in JavaScript?

An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer. To avoid such incidents it is important to be aware of infinite loops so that we can avoid them.

How do you make an infinite loop in JavaScript?

In a case, if it is expected to execute in a browser, a better way to implement an infinite loop Is using setTimeout or setInterval function.


2 Answers

Remove the function call, and take out the quotes. If you don't put the quotes, setTimeout gets a direct reference to the function which it can invoke later. However, if inside a string such as "checkForAllImagesLoaded" or "checkForAllImagesLoaded()", then it will execute the code passed-in when the timeout occurs.

At that time, checkForAllImagesLoaded will be searched for in the global object (window) but it is not defined there, reason being why you're getting the undefined error.

Your code is wrapped in a self-calling anonymous function, and outside of it checkForAllImagesLoaded does not exist. So pass a direct reference to the function in your setTimeout call, instead of a string.

setTimeout(checkForAllImagesLoaded, 20);

setTimeout can be called with either 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);
like image 80
Anurag Avatar answered Oct 10 '22 23:10

Anurag


Remove the () in the settimeout call.

setTimeout('checkForAllImagesLoaded', 20);

like image 41
Byron Whitlock Avatar answered Oct 11 '22 00:10

Byron Whitlock