0

I have the following if condition:

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. Does anybody have an idea why?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Horst Otto
  • 20
  • 4

2 Answers2

0

You should place 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; is run again. More about closures.

Community
  • 1
  • 1
jeroenvisser101
  • 856
  • 10
  • 23
0

you are setting executed to false and then checking to see if it is false :) try putting var executed = false global outside the function.

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

regards

TonySB
  • 13
  • 4