Debouncing Javascript Methods

What is debouncing anyways? Debouncing is any kind of hardware device or software that ensures that only a single signal will be acted upon for a single opening or closing of a contact. Imagine you have a form with a few elements that a user may access thru the tab key, on each element you have an onfocus event that will trigger an Ajax call to the server to acquire some data. You could just imagine how you could kill the server with all those Ajax calls! So that’s where debouncing comes into play. With debouncing your assuring that the method will be triggered in the element that the user intended to, although is not perfect it does work better than Throttling.

With this little method writen by John Hann from Unscriptable.com you can add debouncing functionality to your JS methods.

Javascript

var debounce = function (func, threshold, execAsap) {
 
    var timeout;
 
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null;
        };
 
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
 
        timeout = setTimeout(delayed, threshold || 100);
    };
 
}

Usage

    // using debounce in a constructor or initialization function to debounce
    // focus events for a widget (onFocus is the original handler):
    this.debouncedOnFocus = this.onFocus.debounce(500, false);
    this.inputNode.addEventListener('focus', this.debouncedOnFocus, false);


One Response to “Debouncing Javascript Methods”

  1. Thanks.


Post a Comment



Follow Me