On gists
Debounce, Throttle, Wait (ES6 Utils)
•
JS oneliners
export function debounce(fn, wait){
let timer;
return function(...args){
if(timer) {
clearTimeout(timer); // clear any pre-existing timer
}
const context = this; // get the current context
timer = setTimeout(()=>{
fn.apply(context, args); // call the function if time expires
}, wait);
}
}
export function throttle(fn, wait){
let throttled = false;
return function(...args){
if(!throttled){
fn.apply(this,args);
throttled = true;
setTimeout(()=>{
throttled = false;
}, wait);
}
}
}
export function wait(waitTime, callback = () => {}) {
return new Promise(resolve => {
setTimeout(() => {
callback()
resolve(true)
}, waitTime)
})
}
window.addEventListener('resize', debounce(() => {
console.log('Resized!');
}, 200));
window.addEventListener('scroll', throttle(() => {
console.log('Scrolled!');
}, 200));
debounce-2.js
Raw
#
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// usage
const handleSearch = debounce(() => {
// fetch data
}, 300);