Last active
August 29, 2015 14:25
-
-
Save DerekCuevas/1622dd49ec58380ceb04 to your computer and use it in GitHub Desktop.
Returns a function that has a timeout of 'delay' seconds, the timeout resets every time the function is called, useful for delaying keyboard events when a user is typing.
This file contains hidden or 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
| /** | |
| * Returns a function that has a timeout of 'delay' seconds, | |
| * the timeout resets every time the function is called. However if | |
| * the (optional) except function returns true, the function will not be called. | |
| * | |
| * Useful for delaying and blocking keyboard events when a user is typing. | |
| * | |
| * @param {Number} delay timeout in milliseconds | |
| * @param {Function} fn the base function | |
| * @param {Function} except | |
| * @return {Function} | |
| */ | |
| function make_delay_fn_except(delay, fn, except) { | |
| var watch; | |
| return function () { | |
| var args = Array.prototype.slice.call(arguments); | |
| clearTimeout(watch); | |
| if (except && except.apply(null, args)) { | |
| return; | |
| } | |
| watch = setTimeout(function () { | |
| fn.apply(null, args); | |
| }, delay); | |
| }; | |
| } | |
| var f = make_delay_fn_except(1000, console.log); | |
| for (i = 0; i < 100; i += 1) { | |
| f(i); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment