Skip to content

Instantly share code, notes, and snippets.

@rafacv
Last active October 16, 2015 22:42
Show Gist options
  • Save rafacv/f75fe2ec648e70af6632 to your computer and use it in GitHub Desktop.
Save rafacv/f75fe2ec648e70af6632 to your computer and use it in GitHub Desktop.
Delay responses to events
/*
* Sometimes it's useful to wait for the user to complete the action
* he's engaged on instead of trying to handle it right away. A practical
* example is to avoid flooding servers with tons of autocompletion requests
* for each key stroke the user types in. A more efficient approach is to wait
* until the user feeds enough before attempting make requests for only one or
* two letters.
*
* Usage:
* listenToEventAndDelay(textInput, 'keydown', autoCompleteFunction, 500);
*/
function listenToEventAndDelay(subject, eventName, callback, delay) {
var timeout;
subject.addEventListener(eventName, function (e) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
timeout = null;
callback(e)
}, delay);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment