Search code examples
javascriptthrottlingiife

Why Did Filatov Use an OR Statement?


I've branched Dmitry Filatov's jQuery-Plugins (https://github.com/dfilatov/jquery-plugins) in an effort to learn how this @#^#$% wizard of a man wrote his throttle and debounce wrappers.

Of all the things that make absolutely no sense to me, his throttle wraps the setTimeout() in an IIFE as part of an OR statement:

// why the extra complexity here?
timer || (function() {
   if (needInvoke) {
     fn.apply(ctx, args);
     needInvoke = false;
     timer = setTimeout(arguments.callee, timeout);
   } else {
     timer = null;
   }
})();

As far as I can tell, it just prevents the IIFE from executing if the timer has a value. Is it a matter of performance?


Solution

  • Because of short-circuiting, logical operators can be used as substitutes for if.

    expr1 || expr2
    

    is equivalent to

    if (!expr1) expr2
    

    But since the arguments to || have to be expressions, you can't put statement blocks there. An IIFE can be used to wrap a block of statements in an expression.

    If you undo those transformations, you get the more straightforward code:

    if (!timer) {
      if (needInvoke) {
        fn.apply(ctx, args);
        needInvoke = false;
        timer = setTimeout(arguments.callee, timeout);
      } else {
        timer = null;
      }
    }