Skip to content

Instantly share code, notes, and snippets.

@sunderls
Last active June 1, 2020 15:13
Show Gist options
  • Save sunderls/4c15060b664155297369855dd97a4d35 to your computer and use it in GitHub Desktop.
Save sunderls/4c15060b664155297369855dd97a4d35 to your computer and use it in GitHub Desktop.
throttle/debounce in JavaScript
const debounce = (func, wait, options = {
leading: false,
trailing: true
}) => {
// same timer for leading and trailing
let timer = null
// special flag to skip the trailing call if leading is true
let isCalledForLeading = false
return function () {
// when timer is up, trigger if trailing is true
const delayed = () => {
if (options.trailing && !isCalledForLeading) {
func.apply(this, arguments)
}
timer = null
}
// if no timer , then a instant trigger
if (options.leading && timer === null) {
func.apply(this, arguments)
isCalledForLeading = true
} else {
isCalledForLeading = false
}
// clear time and set a new one
window.clearTimeout(timer)
timer = setTimeout(delayed, wait)
}
}
const throttle = (func, wait, options = {leading: true, trailing: true}) => {
let timer = null
let lastContext = null
let lastArgs = null
return function(...args) {
// 1. if called within cool time, then store it for later call
if (timer !== null) {
lastContext = this
lastArgs = args
return
}
// 2. if other than cool time, execute it
if (options.leading !== false) {
func.call(this, ...args)
} else {
// save for trailing call if needed
lastContext = this
lastArgs = args
}
// 3. set a timeout to clear the cool, time
// and run the stored context
const timeup = () => {
if (options.trailing !== false && lastArgs !== null) {
func.call(lastContext, ...lastArgs)
lastContext = null
lastArgs = null
timer = setTimeout(timeup, wait)
} else {
timer = null
}
}
timer = setTimeout(timeup, wait)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment