Recently I was working on an HTA which contained an element that I wanted to be resized when the window resized. The issue was that I only wanted the resizing to occur after 0.5 seconds elapsed in which the user was not resizing the window. For this reason the debounce function was born (or re-invented since it already is available in other JS libraries):

/**
 * @license Debounce - By Chris West - MIT License
 *
 * Creates a debounced copy of the function which when called will delay the
 * execution until the specified amount of milliseconds have elapsed since the
 * last time it ran.
 * @param {!Function} fnCallback  The function to debounce.  The context and
 *     parameters sent to the debounced function will be sent to this function.
 * @param {number} delay  The amount of milliseconds that must pass since the
 *     last call to this function before fnCallback will be invoked.
 * @param {boolean=} immediate  Optional.  Defaults to false.  Specify true if
 *     the debounce function should run immediately instead of initially waiting
 *     for the delay.  If true is specified, when the debounced function runs,
 *     if the delay has elapsed, the value returned from the debounced function
 *     will be that which was returned by fnCallback.
 * @return {!Function}  The debounced copy of fnCallback.
 */
function debounce(fnCallback, delay, immediate) {
    var timeout, ready = 1;
    return function() {
        var args = arguments, context = this;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            if(!(ready = immediate)) {
                fnCallback.apply(context, args);
            }
        }, delay);
        if(immediate && ready) {
            return ready = 0, fnCallback.apply(context, args);
        }
    };
}

The above debounce function works the same way as Underscore.js’s debounce function. The only difference is that the code is just a tad bit shorter when minified. I will probably end up adding this function to the next version of jPaq, but until then feel free to use the above snippet yourself. 8)


Leave a Reply

Your email address will not be published. Required fields are marked *