views:

20

answers:

1

I have an array of checkboxes in a complex dynamic-html form. Whenever a user clicks one checkbox, a fairly expensive query is generated and submitted to a remote server. I want to delay this submit action depending on the users next action. If the user clicks several checkboxes quickly, all of the first clicks should be discarded, only the last one is processed and eventually submitted after 1 second or so. maybe this is a common problem but I have never worked with timeouts before.

A: 

the method you are trying to employ is called debouncing.
I usually have a generic debounce function in my 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); 
    }; 
};

And then when something needs debouncing, I usually debounce the function,
In your case it might be something like:

$("checkbox").click(debounce(callBackFunction,1000));

where callbackFunction is the function that does your "expensive jquery" and 1000 is the timeout.

Applying the above would mean that callbackFunction is called at 1 second timeouts, if it is called at any shorter intervals, the call is ignored.

pǝlɐɥʞ
that was fast, thanks! has been answered before here on stackoverflow.com.see here for a commented version of khaleds code, and more: http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
knb