Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
//Debounce returns a function, based on input:
//1. trigger function for debouncing - func
//2. time to debounce (waiting time - only call after this amount of secs passed - wait
//3. immediate - true/false whether trigger function immediately or wait until the debouncing time.
//1. Save arguments, save context
//2. Clear timeout - start again the counter
//3. if (immediate and no timeout - aka first run - run it.
//4. set Time out for triggering func with wait time, in which if not immediate (false), then clear timeout and trigger func.
function debounce(func, wait, immediate = false){
var timeout;
return function(){
var context = this, args = arguments;
var later = function(){
timeout = null;
func.apply(context, args);
var callNow = immediate && !timeout;
timeout = setTimeout(later, wait);
if (callNow){
func.apply(context, args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment