tags:

views:

20

answers:

1

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);
                   })();
        };
A: 

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!'; 
Daniel Mendel
@Daniel: The declaration of `a_var` has to be even higher than this!?....`function someFunction(){var a_var; (function why(){ a_var='help I wanna get out!';return a_var;//<-useless? })();};`
cube
It looks like you've got some unnecessary parts in there, it might be helpful to read more about javascript closures: http://www.webreference.com/programming/javascript/rg36/
Daniel Mendel