[英]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:
我希望能够在参数f中执行该函数并设置一些变量(例如变量 ),以便该函数可以使用它们,总的来说这是一个想法:
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 . 浏览器可能只是忽略错误并提醒undefined 。
But anyways, how do I "pass" the variable without changing the scope of it . 但无论如何,如何在不改变变量范围的情况下 “传递”变量。
JavaScript has closures , so you can do this: JavaScript有闭包 ,所以你可以这样做:
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. setInterval
接受两个参数,第二个参数是您希望延迟执行传入函数引用的时间量(以毫秒为单位)。
Given that the lambda function is coming from another scope, you can't use a closure to get the value in the function directly. 鉴于lambda函数来自另一个范围,您不能使用闭包直接获取函数中的值。 You'll have to pass the value to your function directly via a closure, and be prepared to receive it in the lambda:
您必须通过闭包直接将值传递给函数,并准备在lambda中接收它:
function say(f){
var variable = "hey";
setInterval( function(){ f(variable) }, 500 );
}
say(function(yyy){
alert(yyy);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.