Basit
Basit

Reputation: 8606

setTimeout() is not calling function after specified time

I have a code in my js file.

function makeScrollable(wrapper, scrollable){  
    ...
    // Hide images until they are not loaded
    scrollable.hide();

    var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);

    // Set function that will check if all images are loaded
    var interval = setInterval(function(){
        var images = scrollable.find('img');
        var completed = 0;

        if (completed == images.length) {
            clearInterval(interval);

            // Timeout added to fix problem with Chrome
            setTimeout(function(){
                loading.hide();
                ....
            }, 1000); //end of setTimeout(func, delay)

        } //end of if (completed == images.length)

    }, 100); //end of var interval = setInterval(fn, 100)

    ...
}

(function(){
    makeScrollable("div.sc_menu_wrapper", "div.sc_menu");
})(jQuery);

But my timeout function isn't calling. I am still getting the loading Div. Function should be call after 1 sec, which hide the loading div and execute code after. But it isn't happening. What i am doing wrong? Thanks

Upvotes: 1

Views: 468

Answers (1)

Diode
Diode

Reputation: 25135

Wrong position of code.

    var completed = 0;

    if (completed == images.length) {  // This will be true only when there are no images
        clearInterval(interval);


        setTimeout(function(){
            loading.hide();
            ....
        }, 1000); 

    } 

put it outside

var completed = 0;
var interval = setInterval(function(){
    var images = scrollable.find('img');


    if (completed == images.length) {
        clearInterval(interval);

        // Timeout added to fix problem with Chrome
        setTimeout(function(){
            loading.hide();
            ....
        }, 1000); //end of setTimeout(func, delay)

    } //end of if (completed == images.length)

}, 100); //end of var interval = setInterval(fn, 100)

And hope you are incrementing completed somewhere in the code

Upvotes: 1

Related Questions