Search code examples
javascriptperformancecoercion

JavaScript postfix a boolean / one-shot flag for throttling an event


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


Solution

  • Since a number is only falsey at 0

    var isDone = 0;
    
    if (!isDone++) {
        // do stuff
    }
    

    or

    var isProceding = true;
    
    if (isProceding --> false) {
        // do stuff
    }