setTimeout()在指定时间后没有调用函数

时间:2012-03-01 11:16:10

标签: javascript jquery

我的js文件中有代码。

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);

但是我的超时功能没有调用。我还在装载Div。函数应该在1秒后调用,这会隐藏加载div并执行代码。但它没有发生。我做错了什么? 感谢

1 个答案:

答案 0 :(得分:1)

代码位置错误。

    var completed = 0;

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


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

    } 

把它放在外面

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)

并希望您在代码中的某处增加completed