Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active September 1, 2020 22:17
Show Gist options
  • Save GGrassiant/0b893e9a1a4d9349287799d8125e2604 to your computer and use it in GitHub Desktop.
Save GGrassiant/0b893e9a1a4d9349287799d8125e2604 to your computer and use it in GitHub Desktop.
Debouncing & Throttling
const debounce = (func, wait, immediate) => {
let timeout;
return function executedFunction() {
const context = this;
const args = arguments;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
debounceBtn.addEventListener('click', debounce(function() {
console.info('Hey! It is', new Date().toUTCString());
}, 3000));
const throttle = (func, limit) => {
let inThrottle
return function() {
const args = arguments
const context = this
if (!inThrottle) {
func.apply(context, args)
inThrottle = true
setTimeout(() => inThrottle = false, limit)
}
}
}
throttleBtn.addEventListener('click', throttle(function() {
return console.log('Hey! It is', new Date().toUTCString());
}, 1000));
const throttle = (func, limit) => {
let lastFunc
let lastRan
return function() {
const context = this
const args = arguments
if (!lastRan) {
func.apply(context, args)
lastRan = Date.now()
} else {
clearTimeout(lastFunc)
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args)
lastRan = Date.now()
}
}, limit - (Date.now() - lastRan))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment