Last active
November 14, 2019 02:32
-
-
Save alperg/568ef61df6d73019192c63ff33f62a6c to your computer and use it in GitHub Desktop.
Debouncing examples
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
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