Radiant0.3.0-rc.2

debounce

debounce creates a debounced wrapper around any function. The returned function delays invocation until the configured timeout has passed since the last call. It is the functional equivalent of the @debounce decorator, usable without decorators or classes.

Usage

import { debounce } from '@ecopages/radiant/helpers/debounce';
 
const search = debounce((query: string) => {
	console.log('Searching for:', query);
}, 300);
 
search('rad');
search('radi');
search('radiant'); // only this call executes, after 300ms

Parameters

debounce<T>(callback, timeout) accepts:

ParameterTypeRequiredDescription
callbackT extends (...args) => anyYesThe function to debounce.
timeoutnumberYesDelay in milliseconds before execution.

Return Value

Returns a DebouncedFunction<T> with the same call signature as the original, plus three imperative helpers:

MethodReturnsDescription
cancel()voidCancels the pending invocation.
flush()ReturnType<T> | undefinedImmediately executes the pending call and returns its result. Returns the last completed result if nothing is pending.
pending()booleanReports whether a call is currently scheduled.

Imperative Control

const save = debounce(async (data: string) => {
	await fetch('/api/save', { method: 'POST', body: data });
}, 2000);
 
save('draft content');
 
save.pending();  // true
save.flush();    // executes immediately, returns the result
save.pending();  // false
 
save('more content');
save.cancel();   // cancels the scheduled call

Using with a Custom Element

import { RadiantElement } from '@ecopages/radiant';
import { createEventListener } from '@ecopages/radiant/helpers/create-event-listener';
import { debounce } from '@ecopages/radiant/helpers/debounce';
 
class SearchInput extends RadiantElement {
	#search = debounce((query: string) => {
		console.log('Searching:', query);
	}, 300);
 
	constructor() {
		super();
		createEventListener(this, { selector: 'input', type: 'input' }, (event) => {
			this.#search((event.target as HTMLInputElement).value);
		});
	}
 
	override disconnectedCallback() {
		super.disconnectedCallback();
		this.#search.cancel();
	}
}
 
customElements.define('search-input', SearchInput);

Guidelines for Delays

Use CaseRecommended DelayReasoning
Search input300–500msBalance responsiveness with fewer requests.
Window resize200–300msLet layout settle before recomputing.
Auto-save1000–3000msBatch edits and reduce server traffic.

Learn More