Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active February 10, 2026 17:13
Show Gist options
  • Select an option

  • Save glaucocustodio/22531b0181f39412cc50e519e71ddf30 to your computer and use it in GitHub Desktop.

Select an option

Save glaucocustodio/22531b0181f39412cc50e519e71ddf30 to your computer and use it in GitHub Desktop.
Throttle & Debounce functions
/*
Throttle ensures fn runs at most once per delay period (default 1 second).
On the first call, it immediately invokes fn and sets a timeout.
Any subsequent calls during the delay window are ignored.
Once the timeout expires, timeoutId resets to null, allowing the next call through.
This is a "leading-edge" throttle — the function fires right away, then locks out for delay ms.
Note that calls made during the cooldown are silently dropped (not queued), so the last trailing call can be lost.
*/
export function throttle(fn, delay = 1000) {
let timeoutId = null
return (...args) => {
if (!timeoutId) {
fn(...args)
timeoutId = setTimeout(() => timeoutId = null, delay)
}
}
}
/*
Debounce delays execution of fn until the caller stops calling for delay ms (default 1 second).
Every call resets the timer (clearTimeout + new setTimeout).
fn only fires once the calls have "settled" — i.e., no new invocation arrives within the delay window.
It preserves this context via fn.apply(context, args).
This is a "trailing-edge" debounce — the function fires at the end of the quiet period.
*/
export function debounce(fn, delay = 1000) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(context, args), delay);
};
}
// Usage example in a Stimulus controller
import { debounce } from "../helpers/frequency_helpers"
export default class extends Controller {
initialize() {
this.updateUi = debounce(this.updateUi.bind(this), 500)
}
updateUi(event) {
// function will be called respecting the one of the frequency helpers..
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment