Last active
February 10, 2026 17:13
-
-
Save glaucocustodio/22531b0181f39412cc50e519e71ddf30 to your computer and use it in GitHub Desktop.
Throttle & Debounce functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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