Last active
November 17, 2015 19:32
-
-
Save larryprice/56d0091815d79db390af to your computer and use it in GitHub Desktop.
How does _'s debounce work?
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
var _ = {}; | |
_.debounce = function (func, wait, immediate) { | |
var timeout, start, that, args; | |
var later = function () { | |
if (Date.now() - start >= wait && !immediate) { | |
func.apply(that, args); | |
timeout = null; | |
} | |
}; | |
return function () { | |
start = new Date(); | |
that = this; | |
args = arguments; | |
if (immediate && !timeout) func.apply(that, args); | |
if (!timeout) timeout = setTimeout(later, wait); | |
}; | |
} | |
var f = function (str) { | |
console.log(str); | |
}; | |
var debouncedF = _.debounce(f, 500); | |
debouncedF(1); | |
debouncedF(2); | |
debouncedF(3); | |
debouncedF(4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment