debounce
debounce wraps a function so that it only runs once a given amount of time has passed without it being called again. Every time the returned function is invoked, the pending timer is reset — so the wrapped function only fires after things have settled.
This is invaluable for high-frequency events like resize, scroll, input or keyup, where you don't want to run expensive work on every single event.
It accepts:
| Argument | Type | Description |
|---|---|---|
fn | Function | The function to debounce. |
wait | number | How long, in milliseconds, to wait after the last call. |
Usage examples
Debouncing a search input
- 2.0 Build
- 1.0 Build
this.listeners.add(this.els.input.element, 'input', window.BAO.utils.debounce((event) => {
console.log('Searching for', event.target.value)
}, 300))
this.listeners.add(this.els.input, 'input', debounce((event) => {
console.log('Searching for', event.target.value)
}, 300))
Debouncing a resize handler
- 2.0 Build
- 1.0 Build
this.listeners.add(window, 'resize', window.BAO.utils.debounce(this.updateImage, 100))
this.listeners.add(window, 'resize', debounce(this.updateImage, 100))