How to properly debounce ajax requests
Just debounce the function that does the actual work and I wouldn't load an entire library for this.
var debouncedSomeFunction = debounce(someFunction, 1500);
debouncedSomeFunction();
debouncedSomeFunction();
debouncedSomeFunction();
setTimeout(debouncedSomeFunction, 2000);
function debounce(fn, bufferInterval) {
var timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(fn.apply.bind(fn, this, arguments), bufferInterval);
};
}
function someFunction() {
log('someFunction executed');
}
function log(text) {
document.body.appendChild(document.createTextNode(text));
document.body.appendChild(document.createElement('br'));
}
Not sure if there can be a "proper" way to do this.
Having said that underscore has such a utility that will create a debounced version of your function...
var MyToggleDebounced = _.debounce(MyToggleFunction, 1500);
then use MyToggleDebounced
in your click handler.
Link to debounce docs on underscorejs
Take a look at the annotated source for how they do it.