Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Created January 16, 2018 17:45
Show Gist options
  • Save ahmed-musallam/5c93d44f03bb917e6aede817b504e29b to your computer and use it in GitHub Desktop.
Save ahmed-musallam/5c93d44f03bb917e6aede817b504e29b to your computer and use it in GitHub Desktop.
Wait for a javascript namespace to become available, with timeout!
// in this example, we wait for jquery to become available.
waitFor("$",1000*60,function(){
console.log('jQuery is ready to be used!');
})
/**
* 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