Last active
December 22, 2018 09:55
-
-
Save shalvah/b8dd8db9adf14a7f77f53a9ee05e32ab to your computer and use it in GitHub Desktop.
Implementation of debounce functionality in JavaScript
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
function debounce(f, t) { | |
return function (args) { | |
let previousCall = this.lastCall; | |
this.lastCall = Date.now(); | |
if (previousCall && ((this.lastCall - previousCall) <= t)) { | |
clearTimeout(this.lastCallTimer); | |
} | |
this.lastCallTimer = setTimeout(() => f(args), t); | |
} | |
} | |
let logger = (args) => console.log(`My args are ${args}`); | |
// debounce: call the logger when two seconds have elapsed since the last call | |
let debouncedLogger = debounce(logger, 2000); | |
debouncedLogger([1, 2, 3]); | |
debouncedLogger([4, 5, 6]); | |
debouncedLogger([7, 8, 9]); | |
// "My args are 7, 8, 9" - logged after two seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment