Skip to content

Instantly share code, notes, and snippets.

@Dodotree
Last active November 23, 2022 18:23
Show Gist options
  • Select an option

  • Save Dodotree/bd8e1752dda7b6b293b46016293b309e to your computer and use it in GitHub Desktop.

Select an option

Save Dodotree/bd8e1752dda7b6b293b46016293b309e to your computer and use it in GitHub Desktop.
Minimalistic JS throttle function to limit calls to any callback function to "once per Nms", most useful with N between 100-300. Can be used on the back end too depending on time delay functions available.
const throttle = (delayFunc, cancelFunc) => (callback, delay) => {
let lastFunc
let lastExecTime
return function (...args) {
const context = this
const elapsed = Date.now() - lastExecTime
function execCallback () {
lastExecTime = Date.now()
callback.apply(context, args)
}
if (!lastExecTime) {
execCallback()
} else {
cancelFunc(lastFunc)
if (elapsed >= delay) {
execCallback()
} else {
lastFunc = delayFunc(execCallback, delay - elapsed)
}
}
}
}
const throttleTout = throttle(setTimeout, clearTimeout)
// alternative can be or similar throttle(requestAnimationFrame, cancelAnimationFrame)
// Example
// area.addEventListener("mousemove", throttleTout(myCallBack("something"), 200));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment