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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With