Skip to content

Instantly share code, notes, and snippets.

@alperg
Last active November 14, 2019 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alperg/568ef61df6d73019192c63ff33f62a6c to your computer and use it in GitHub Desktop.
Save alperg/568ef61df6d73019192c63ff33f62a6c to your computer and use it in GitHub Desktop.
Debouncing examples
const debounce1 = (fn, delay) => {
let timer = null;
return function (...args) {
const context = this;
timer && clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
const debounce2 = function(fn, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => fn.apply(context, args), delay);
};
};
const debounce3 = function(fn, delay, immediate) {
let timer;
return function() {
const context = this;
const args = arguments;
const callNow = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(function() {
timer = null;
if (!immediate) {
fn.apply(context, args);
}
}, delay);
if (callNow) {
fn.apply(context, args);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment