[英]Self-closing if statement/loop
I have the following if condition: 我有以下if条件:
function turnLedOn1(evt) {
led.on();
var executed = false;
if (!executed) {
executed = true;
checkin1 = timestamp;
alert('checkin1');
}
}
The if loop should only be executed once, but i get like 15 alerts until it stops. if循环只能执行一次,但是我会收到15条警报,直到停止为止。 Does anybody have an idea why? 有人知道为什么吗?
You should place var executed = false;
您应该将var executed = false;
放在其中var executed = false;
outside of your function closure. 在函数关闭之外。
var executed = false;
function turnLedOn1(evt) {
led.on();
if (!executed) {
executed = true;
checkin1 = timestamp;
alert('checkin1');
}
}
When a variable is declared in a function, it can only be read from that 'closure'. 在函数中声明变量时,只能从该“闭包”中读取它。 When the function runs again, the variable is reset because var ... = false;
当函数再次运行时,将重置变量,因为var ... = false;
is run again. 再次运行。 More about closures. 有关关闭的更多信息。
you are setting executed to false and then checking to see if it is false :) try putting var executed = false global outside the function. 您可以将execute设置为false,然后检查是否为假:)尝试将var execute = false全局置于函数之外。
var executed = false;
if (!executed) {
...
}
regards 问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.