Skip to content

Instantly share code, notes, and snippets.

@aj07mm
Created July 4, 2019 19:06
Show Gist options
  • Save aj07mm/41f422a837d0c1b00e74ca5c23b738f4 to your computer and use it in GitHub Desktop.
Save aj07mm/41f422a837d0c1b00e74ca5c23b738f4 to your computer and use it in GitHub Desktop.

Revisions

  1. aj07mm created this gist Jul 4, 2019.
    33 changes: 33 additions & 0 deletions debounce_throttling.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    function debounce(fn, delay) {
    var timer = null;
    return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
    fn.apply(context, args);
    }, delay);
    };
    }

    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);
    }
    };
    }