ict.ken.be

 

Javascript debounce vs throttle function

Related Posts

Categories: Javascript

Debounce is often confused with throttle, mainly because some frameworks like knockout use the wrong naming... not that it matters much, but here you can see the difference in code.

Debounce (fire after pause)

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}
$('input.search').keypress(debounce(function (event) {
  // do the ajax call
}, 250));

Throttle (keep firing with pauses)

function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last, deferTimer;
  return function () {
    var context = scope || this;
    var now = +new Date, args = arguments;
    if (last && now < last + threshhold) {
      // hold on to it
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        fn.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}
$('body').on('mousemove', throttle(function (event) {
  console.log('tick');
}, 1000));