$(document).ready()|| setTimeout的?

时间:2016-10-30 00:38:44

标签: jquery

我有代码(问题不是必需的)需要在$(document).ready()之后执行,如果加载窗口让我们说5秒钟。

我试图搞清楚,但我无法在网上找到任何东西。希望有人可以帮助我!

(我知道如何在2个语句中分开,但我需要将它放在OR语句中。)

编辑:让人们更清楚。 等待,直到文档准备就绪,如果dom构建 OR ,如果5秒后文档仍然没有准备好,但是窗口加载,只需执行该功能。

2 个答案:

答案 0 :(得分:3)

使用setTimeout来安排操作,然后将clearTimeout放在$(document).ready()中,以便在文档提前就绪时取消它。

并使用变量来判断该功能是否已由计时器运行,因此您不必在就绪功能中再次执行该操作。

var functionDone = false;
var timeout = setTimeout(function() {
    someFunction();
    functionDone = true;
}, 5000);
$(document).ready(function() {
    if (!functionDone) {
        clearTimeout(timeout);
        someFunction();
    }
});

答案 1 :(得分:0)

对于可恢复的解决方案,您可以创建一个生成超时包装器,如下所示:

// return a new function to pass to document.ready
// that has a timeout wrapper on it
function timeoutFn(fn, t) {
    var fired = false;
    var timer;
    function run() {
        clearTimeout(timer);
        timer = null;
        if (!fired) {
            fired = true;
            fn();
        }
    }
    timer = setTimeout(run, t);
    return run;
}

然后,就像这样使用它:

$(document).ready(timeoutFn(function() {
    // put code here for function that will be called
    // at the earlier occurrence of 5 seconds or document.ready
}, 5000));

或者,您可以将其设为jQuery插件:

jQuery.fn.readyTimeout = function(fn, t) {
    return $(document).ready(timeoutFn(fn, t));
}

并且,像这样使用它:

$(document).readyTimeout(function() {
    // put code here for function that will be called
    // at the earlier occurrence of 5 seconds or document.ready
}, 5000);
相关问题