0x0049 icon

Debounce & throttle

0x0049 | PRO | 10/10/17 12:53:05 AM UTC | 0 ⭐ | 242 👁️ | Never ⏰ | []
JavaScript |

1.04 KB

|

None

|

0 👍

/

0 👎

/**
 * Returns a function that, as long as it continues to be invoked, will not
 * be triggered. The function will be called after it stops being called for
 * N milliseconds.
 *
 * @param  {Function} fn
 * @param  {Number}   wait In milliseconds.
 * @return {Function}
 */
Showcase.debounce = function (fn, wait) {
    var timeout;
    return function () {
        clearTimeout(timeout);
        var that = this, args = arguments;
        timeout = setTimeout(function () {
            fn.apply(that, args);
        }, wait);
    };
};
 
/**
 * Returns a function that will fire every N milliseconds at most.
 *
 * @param {Function} fn
 * @param {Number}   threshold
 */
Showcase.throttle = function (fn, threshhold) {
    var last, deferTimer;
    return function () {
        var that = this, args = arguments, now = new Date().getTime();
        if (last && now < last + threshhold) {
            clearTimeout(deferTimer);
            deferTimer = setTimeout(function () {
                last = now;
                fn.apply(that, args);
            }, threshhold);
        } else {
            last = now;
            fn.apply(that, args);
        }
    };
};

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎