Created
January 16, 2018 17:45
-
-
Save ahmed-musallam/5c93d44f03bb917e6aede817b504e29b to your computer and use it in GitHub Desktop.
Wait for a javascript namespace to become available, with timeout!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in this example, we wait for jquery to become available. | |
waitFor("$",1000*60,function(){ | |
console.log('jQuery is ready to be used!'); | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A function to wait for a namespace to be available | |
* @param {*} namespace the namespace to wait for | |
* @param {*} timeout The timout in milliseconds | |
* @param {*} callback The callback to perform once the namespace is available | |
* @param {*} interval time (in milisecponds) between each call. Default 100. | |
*/ | |
function waitFor(namespace, timeout, callback, interval) { | |
var defaultInterval = interval>=0 ? interval : 100; // try every 100 milliseconds (10 times per second) number chosen to enhance performance; | |
if (window[namespace]) { // namespace exists | |
callback(); | |
} else if (timeout <= 0) { // check if we reached the timeout | |
return; | |
} else { | |
setTimeout(function() { // namespace does not exist, wait interval amount then try again; | |
waitFor(namespace, timeout - defaultInterval, callback, interval); | |
}, defaultInterval); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment