cube
cube

Reputation: 1802

self invoking function with setTimeout closure, variable access

How would I get access to the a_var that is in setTimeout, from the outter someFunction?

Thanks.

function someFunction(){
             (function why(){
                       setTimeout(function(){

                          var a_var='help I wanna get out!';
                         return a_var;//<-useless?

                      }, 25);
                   })();
        };

Upvotes: 1

Views: 1007

Answers (1)

Daniel Mendel
Daniel Mendel

Reputation: 10003

You have to declare a_var in a higher scope, like so:

var a_var = 'I can help from here';
function someFunction(){
  setTimeout(function(){
    a_var = "help I wanna get out!";
  }, 25);
}
someFunction();
console.log(a_var); // logs 'I can help from here'
setTimeout(function(){
   console.log(a_var);
}, 30); // logs 'help I wanna get out!'; 

Upvotes: 1

Related Questions