Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout() on recursive function within a self invoking function

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?

like image 806
user967722 Avatar asked Jan 11 '12 15:01

user967722


People also ask

What is the use of setTimeout () in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

Is setTimeout recursive?

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);

Does setTimeout block execution?

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.


2 Answers

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/

like image 193
Gabriele Petrioli Avatar answered Nov 14 '22 21:11

Gabriele Petrioli


You could also use a real anonymous function to avoid scoping issues:

(function() {
    if(typeof(myLib) == 'undefined')
        setTimeout(arguments.callee, 50);
    else
        // loaded
})()
like image 36
georg Avatar answered Nov 14 '22 21:11

georg