Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Pass a variable from one function to another, using setInterval()?

So I have a function that loops executing a function, example:

function(f){
  var variable;
  for(z = 0; z < 10; z++){
    variable = "cool";         
    setInterval(f)
  }

Btw, the real function is MUCH more complex than this but it's the same theory. I want to be able to execute the function in argument f and set some variables (ex. variable) so that this function can use them, in a whole this is the idea:

function say(f){
   var variable = "hey";
   setInterval(f);
}
say(function(){
   alert(variable)
});

Here, one should get an alert box saying hey. That's the theory, but it wont work:

Variable "variable" isn't defined

The browser will probably just ignore the error and alert undefined.

But anyways, how do I "pass" the variable without changing the scope of it.

like image 210
JCOC611 Avatar asked Sep 04 '26 03:09

JCOC611


2 Answers

JavaScript has closures, so you can do this:

var x = 0;
setInterval(function() {
   //do something with x
}, 1000);

In your specific case, you should do this:

function say(f){
   var variable = "hey";
   setInterval(function() { 
       f(variable); //invoke the say function's passed-in "f" function, passing in "hey"
   }, 1000);
}
say(function(arg){
    //arg will be "hey"
    alert(arg);
});

setInterval takes two arguments, the second being the amount of time (in milliseconds) that you wish to delay execution of the passed-in function reference.

like image 159
Jacob Relkin Avatar answered Sep 05 '26 18:09

Jacob Relkin


If you prefer to have a function without parameter, you could consider using the call or apply method:

function say(f){
   var variable = "hey";
   setInterval(function() { 
       f.call(variable); // set the context
   }, 1000);
}
say(function(){
    alert(this);
});
like image 23
William Niu Avatar answered Sep 05 '26 18:09

William Niu