Last active
October 16, 2015 22:42
-
-
Save rafacv/f75fe2ec648e70af6632 to your computer and use it in GitHub Desktop.
Delay responses to events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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