$(document).ready()|| setTimeout? [英] $(document).ready() || setTimeout?
问题描述
我有代码(对于问题来说不是必需的),需要在$(document).ready()或之后执行,如果窗口加载了5秒钟.
I have code (not necessary for the question) which needs to be executed after $(document).ready() or if the window is loaded for let's say 5 seconds.
我试图弄清楚,但是我在网上找不到任何东西.希望这里有人能帮助我!
I tried to figure it out, but I couldn't find anything on the web. Hope someone here can help me!
(我知道如何像2条语句一样将其分开,但是我需要将其放在OR语句中.)
(I know how to do it separate like in 2 statements, but I need to put it in a OR statement.)
使人们更清楚. 等待,直到文档准备就绪,也可以建立域或,如果在5秒钟后文档仍未准备好,但窗口已加载,则只需执行该功能即可. >
To make it more clear for people. Either wait till the document is ready aka dom is builded OR if after 5 seconds the document still isn't ready BUT the window is loaded, just execute the function.
推荐答案
使用setTimeout
安排操作,然后将clearTimeout
放在$(document).ready()
中以取消该操作(如果文档准备得更快).
Use setTimeout
to schedule the operation, then put clearTimeout
in $(document).ready()
to cancel it if the document becomes ready sooner.
并使用一个变量来判断该函数是否已由计时器运行,因此您无需在ready函数中再次进行此操作.
And use a variable to tell if the function has already been run by the timer, so you don't do it again in the ready function.
var functionDone = false;
var timeout = setTimeout(function() {
someFunction();
functionDone = true;
}, 5000);
$(document).ready(function() {
if (!functionDone) {
clearTimeout(timeout);
someFunction();
}
});
这篇关于$(document).ready()|| setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!