I have a click
event that is triggered from another place automatically for the first time. My problem is that it runs too soon, since the required variables are still being defined by Flash and web services. So right now I have:
(function ($) {
$(window).load(function(){
setTimeout(function(){
$('a.play').trigger("click");
}, 5000);
});
})(jQuery);
The problem is that 5 seconds for a person with a slow internet connection could be too fast and vice versa, for a person with a fast internet connection, it's too slow.
So how should I do the delay or timeout until someVariable
is defined?
With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true
Also you don't have to use setTimeout in this case just make ready function asynchronous...
Here's an example where all the logic for waiting until the variable is set gets deferred to a function which then invokes a callback that does everything else the program needs to do - if you need to load variables before doing anything else, this feels like a neat-ish way to do it, so you're separating the variable loading from everything else, while still ensuring 'everything else' is essentially a callback.
I have upvoted @dnuttle's answer, but ended up using the following strategy:
It is tested and working! ;)
Gist: https://gist.github.com/dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c
Shorter way:
You can also pass arguments
The following will keep looking for someVariable until it is found. It checks every 0.25 seconds.
I would prefer this code: