简体   繁体   中英

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 .

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.

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

Given that the lambda function is coming from another scope, you can't use a closure to get the value in the function directly. You'll have to pass the value to your function directly via a closure, and be prepared to receive it in the lambda:

function say(f){
   var variable = "hey";
   setInterval( function(){ f(variable) }, 500 );
}
say(function(yyy){
   alert(yyy);
});
function say(f){
  var variable = "hey";
  setInterval(function(){
    f.call(null, variable);
  }, 1000);
}
say(function(variable){
   alert(variable)
});

By using the call method on the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM