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

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

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

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

编辑:让人们更清楚。 要么等到文档准备就绪,也要建立dom, 或者如果5秒后文档仍然没有准备好,但是窗口加载,只需执行该function。

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

并使用变量来判断该函数是否已由定时器运行,因此您不必在就绪函数中再次执行该函数。

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

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

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