Pandafoxxxx Pandafoxxxx - 2 months ago 25
jQuery Question

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

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!

(I know how to do it separate like in 2 statements, but I need to put it in a OR statement.)

Edit: 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.


Use setTimeout to schedule the operation, then put clearTimeout in $(document).ready() to cancel it if the document becomes ready sooner.

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() {
    functionDone = true;
}, 5000);
$(document).ready(function() {
    if (!functionDone) {