Created
February 11, 2018 12:01
-
-
Save mayashavin/00f0977e4021ea7bf37c71d7f7d7774b to your computer and use it in GitHub Desktop.
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 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. | |
//Logic: | |
//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; | |
if(!immediate){ | |
func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(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