自解密if语句/循环

时间:2014-03-09 15:13:24

标签: javascript if-statement

我有以下条件:

function turnLedOn1(evt) {
    led.on();
    var executed = false;
    if (!executed) {
        executed = true;
        checkin1 = timestamp;
        alert('checkin1');
    }
}

if循环应该只执行一次,但是我会得到15个警报,直到它停止。有人知道为什么吗?

2 个答案:

答案 0 :(得分:0)

您应该将var executed = false;放在函数闭包之外。

var executed = false;
function turnLedOn1(evt) {
    led.on();
    if (!executed) {
        executed = true;
        checkin1 = timestamp;
        alert('checkin1');
    }
}

当在函数中声明变量时,只能从该“闭包”中读取它。当该函数再次运行时,该变量将被重置,因为再次运行var ... = false;More about closures.

答案 1 :(得分:0)

您将执行设置为false,然后检查是否为false :)    尝试将var execution = false global放在函数外部。

 var executed = false;
 if (!executed) {
    ...
 }

问候