Created
July 3, 2018 17:41
-
-
Save lon-io/a56b620f3e65bb0d56ea9c8236ca0a1d to your computer and use it in GitHub Desktop.
A Javascript function to Debounce other functions
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
// Debounce function | |
let debounce = (func, delay) => { | |
let timeout; | |
return (...args) => { | |
// If this function is called again, and there's a timeout defined, clear it; | |
if (timeout) clearTimeout(timeout); | |
// Set a timeout to call the original function, after the `delay` | |
timeout = setTimeout(() => { | |
func(...args); | |
}, delay); | |
}; | |
}; | |
// Test | |
let log = (...args) => { | |
console.log(...args); | |
} | |
let debouncedLog = debounce(log, 3000); | |
debouncedLog('I won\'t run'); | |
setTimeout(() => { | |
debouncedLog('I will run! oh wait! :('); | |
}, 2000); | |
debouncedLog('I won\'t run either'); | |
setTimeout(() => { | |
debouncedLog('I should run, but won\'t'); | |
debouncedLog('Yaay!', 'I will defo. run'); | |
}, 4000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment