Skip to main content

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:

ArgumentTypeDescription
fnFunctionThe function to debounce.
waitnumberHow long, in milliseconds, to wait after the last call.

Usage examples

Debouncing a search input

this.listeners.add(this.els.input.element, 'input', window.BAO.utils.debounce((event) => {
console.log('Searching for', event.target.value)
}, 300))

Debouncing a resize handler

this.listeners.add(window, 'resize', window.BAO.utils.debounce(this.updateImage, 100))