Last active
November 19, 2020 10:20
-
-
Save gsusmonzon/134825297dd72d15f8697398ab10b159 to your computer and use it in GitHub Desktop.
Vanilla Javascipt debounce utility
This file contains hidden or 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 utility based on `underscore` debouce, but simpler | |
* usage: `_debounce(onScrollEvent, 100, true)` | |
* usually you want atBeginning set to false. | |
* use atBeginning if you want `func` is called when teh sequence of calls starts, | |
* instead of waiting until `wait` ms have passed without more calls | |
*/ | |
window._debounce = window._debounce || function(func, wait, atBeginning) { | |
var timeout; | |
if (atBeginning){ | |
return function() { | |
var context = this, args = arguments; | |
var callNow = !timeout; | |
timeout && clearTimeout(timeout); | |
timeout = setTimeout(function() { | |
timeout = null; | |
func.apply(context, args); | |
}, wait); | |
if (callNow) return func.apply(this, args); | |
} | |
} else { | |
return function() { | |
var context = this, args = arguments; | |
timeout && clearTimeout(timeout); | |
timeout = setTimeout(function() { | |
timeout = null; | |
func.apply(context, args); | |
}, wait); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment