Appearance
Debounce
A Service for creating debounced functions with manual control over execution and cancellation. Perfect for optimizing performance in scenarios like search inputs, API calls, and event handlers.
Features
- Manual Control: Explicit
run()andcancel()methods for fine-grained control - Memory Efficient: Proper cleanup of timers
- Flexible: Works with any callback function
Service Reference
Types
typescript
type DebounceHandler<T = void> = {
run: (arg?: T) => void;
cancel: () => void;
}createDebounce
Creates a debounced handler with manual control over execution and cancellation.
typescript
const createDebounce = <T = void>(
callback: (arg?: T) => void,
delay: number
): DebounceHandler<T>;Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (arg?: T) => void | The function to be debounced, optionally receiving an argument |
delay | number | The delay in milliseconds before execution |
Returns
DebounceHandler<T> - An object with run and cancel methods
run(arg?: T): Starts or restarts the debounce timer. You can optionally pass an argument which will be provided to the callback when executed.cancel(): Cancels the pending execution and clears the timer
Usage Examples
Without arguments
vue
<template>
<input type="text" @input="debounce.run()" placeholder="Type something...">
<button @click="debounce.cancel()" class="btn">Stop Debounce</button>
</template>
<script setup lang="ts">
import CreateDebounce from 'dolphin-components';
const debounce = CreateDebounce(() => {
alert('Debounced function executed!');
}, 3000);
</script>With arguments
vue
<template>
<input type="text" @input="(e) => debounce.run(e.target.value)" placeholder="Type something...">
<button @click="debounce.cancel()" class="btn">Stop Debounce</button>
</template>
<script setup lang="ts">
import CreateDebounce from 'dolphin-components';
const debounce = CreateDebounce<string>((inputValue) => {
alert(`Debounced function executed with input: ${inputValue}`);
}, 3000);
</script>Common Use Cases
- Search Inputs: Debounce search queries as user types
- API Calls: Prevent rapid-fire requests
- Validation: Delay validation until user finishes input
Best Practices
- Choose Appropriate Delays
- Always Cancel on Cleanup: Prevent memory leaks by canceling debounced functions when components unmount
- Handle Edge Cases: Check for empty inputs or invalid states before execution