Skip to content

Instantly share code, notes, and snippets.

@bhenderson
Created December 6, 2017 18:37
Show Gist options
  • Save bhenderson/c44d5ca83666832aacc20f8acbcebce8 to your computer and use it in GitHub Desktop.
Save bhenderson/c44d5ca83666832aacc20f8acbcebce8 to your computer and use it in GitHub Desktop.
JS debounce and loop
function debounce(func, wait, immediate) {
var timeout, context, args;
return function() {
context = this, args = arguments;
if (immediate && !timeout) func.apply(context, args);
timeout = timeout || setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
};
}
function loop(func, wait, times) {
if (times == 0) return;
func(times)
var timeout = setTimeout(function() {
timeout = loop(func, wait, times-1) || timeout;
}, wait);
return function() { typeof timeout === "function" ? timeout() : clearTimeout(timeout); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment