0

I want to use a flag once, then convert it to false no matter what, after the expression returns the truthiness:

var isProceding = true;
someObject.addEventListener("someEvent", doOnce); // event fires many times

function doOnce () {
    if (isProceding) {
        isProceding = false; // i want to join this line with the previous
        // do stuff
        someObject.removeEventListener("someEvent", doOnce);
    }
}

from jsperf

  1. if (!isDone++) { 343,020,200 single coercion post fix

  2. if (isProceding && isProceding--) { 342,466,581 short circuit post fix

  3. if (isProceding) { isProceding = false; 338,360,292 standard

  4. if (0 < isProceding--) { 278,447,221 comparison coercion post fix

  5. if (isProceding --> false) { 9,983,236 double coercion postfix

Community
  • 1
  • 1
neaumusic
  • 10,027
  • 9
  • 55
  • 83
  • Why do you need a flag at all, if it's just supposed to fire once, just remove the event listener ? – adeneo Dec 08 '15 at 00:12
  • i dont believe removing the listener will clear the queued callstack – neaumusic Dec 08 '15 at 00:42
  • 1
    Ah, so you're using the variable inside the event handler to stop asynchronous code from running after the handler is removed then. – adeneo Dec 08 '15 at 00:53

1 Answers1

1

Since a number is only falsey at 0

var isDone = 0;

if (!isDone++) {
    // do stuff
}

or

var isProceding = true;

if (isProceding --> false) {
    // do stuff
}
neaumusic
  • 10,027
  • 9
  • 55
  • 83
jcaron
  • 17,302
  • 6
  • 32
  • 46