jquery throttle methods

Benchmark created by mekwall on


Description

I put this test together after reading John Resig's blog post Learning from twitter and the accompanied comments. Found here: http://ejohn.org/blog/learning-from-twitter

Since I dislike the idea of having a backround poll I quickly threw together a solution where I used a simple if-statement to check if a timer was running or not. By implementing this solution into Balázs Galambosi's method I found a very nice and fast solution as this test will show.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
  // by balázs galambosi
  var throttle1 = (function () {
    return function (fn, delay) {
      delay || (delay = 100);
      var last = +new Date;
      return function () {
        var now = +new Date;
        if (now - last > delay) {
          fn.apply(this, arguments);
          last = now;
        }
      };
    };
  })();
  
  // by marcus ekwall
  var throttle2 = function(fn, delay) {
      delay || (delay = 100);
      var throttle = false;
      return function(){
          if (throttle) { return; }
          throttle = setTimeout(function(){ throttle = false; }, delay);
          fn.apply(this, arguments);
      };
  };
  
  // by remy sharp
  var throttle3 = function(fn, delay) {
      var timer = null;
      return function () {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      };
    }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
throttle by Balázs Galambosi
throttle1(function(){ return true; });
ready
throttle by Marcus Ekwall
throttle2(function(){ return true; });
ready
throttle by Remy Sharp
throttle3(function(){ return true; });
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.