@debounce
The @debounce decorator delays the execution of a method until a specified time has passed since its last invocation. This is essential for performance when handling frequent events like scrolling, resizing, or typing.
Usage
import { RadiantElement, customElement, debounce } from '@ecopages/radiant';
@customElement('search-input')
export class SearchInput extends RadiantElement {
@debounce(300)
performSearch(query: string) {
console.log('Searching for:', query);
// Expensive search operation
}
@onEvent({ selector: 'input', type: 'input' })
handleInput(event: InputEvent) {
const query = (event.target as HTMLInputElement).value;
this.performSearch(query);
}
}
Parameters
| Parameter | Type | Required | Description |
|---|
delay | number | Yes | Delay in milliseconds before execution. |
Common Use Cases
Window Resize
@customElement('responsive-chart')
export class ResponsiveChart extends RadiantElement {
@debounce(250)
updateDimensions() {
this.redrawChart();
}
@onEvent({ window: true, type: 'resize' })
handleResize() {
this.updateDimensions();
}
}
Auto-Save
@debounce(2000)
async saveContent() {
await fetch('/api/save', {
method: 'POST',
body: JSON.stringify({ content: this.content })
});
}
@onEvent({ selector: 'textarea', type: 'input' })
handleInput(event: InputEvent) {
this.content = (event.target as HTMLTextAreaElement).value;
this.saveContent();
}
Guidelines for Delays
| Use Case | Recommended Delay | Reasoning |
|---|
| Search input | 300-500ms | Balance between responsiveness and API calls. |
| Window resize | 200-300ms | Smooth but not too delayed. |
| Auto-save | 1000-3000ms | Reduce server load, batch changes. |
NOTE
Debounced methods do not return values immediately and always returned void (or a Promise that resolves when execution completes).
Learn More
- @bound - Often combined with
@debounce.
- @onEvent - Event handlers that benefit from debouncing.