I want to distribute my code as a self-envoking anonymous functions, as I see many do. Also, within my code I have to monitor for another lib loading, so I can use it when it's available.
(function(window, document, undefined) {
staffHappens();
var initMyLib = function() {
if (typeof(myLib) == 'undefined') {
setTimeout("initMyLib()", 50);
} else {
useMyLib();
}
}
moreStaffHappens();
initMyLib(); //-> initMyLib is undefined
})(this, document);
How can this error occur? Should initMyLib be inside the scope of the enclosing (self-envoking) function?
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
JavaScript Intervals and Timeouts Recursive setTimeout To repeat a function indefinitely, setTimeout can be called recursively: function repeatingFunc() { console. log("It's been 5 seconds. Execute the function again."); setTimeout(repeatingFunc, 5000); } setTimeout(repeatingFunc, 5000);
Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.
change setTimeout("initMyLib()", 50);
to setTimeout(initMyLib, 50);
When you pass a string as an argument it will try to evaluate it when the timeout is fired, but it will run in the global scope. And your method does not exist in the global scope.
Demo at http://jsfiddle.net/gaby/zVr7L/
You could also use a real anonymous function to avoid scoping issues:
(function() {
if(typeof(myLib) == 'undefined')
setTimeout(arguments.callee, 50);
else
// loaded
})()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With