$(document).ready()|| setTimeout? [英] $(document).ready() || setTimeout?

查看:84
本文介绍了$(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆