Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  34] [ 7]  / answers: 1 / hits: 19979  / 13 Years ago, wed, january 11, 2012, 12:00:00

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?


More From » closures

 Answers
8

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/


[#88080] Tuesday, January 10, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hector

Total Points: 726
Total Questions: 103
Total Answers: 100

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;