smart-throttle-debounce
v3.0.1
Published
**A lightweight, zero-dependency utility that intelligently combines throttling and debouncing for smarter event handling.**
Readme
⚡ smart-throttle-debounce
A lightweight, zero-dependency utility that intelligently combines throttling and debouncing for smarter event handling.
🚀 Why Use This?
Handling rapid-fire events like scroll, resize, or input can overwhelm performance.
Traditional solutions:
- 🐢 Throttling: Limits how often a function runs. Triggers during the event stream.
- ⏲️ Debouncing: Delays function until the event stream stops.
smart-throttle-debounce combines them for smarter control:
- ✅ Immediate execution on the first event
- ✅ Throttled control during the event burst
- ✅ Final execution after the events stop
📦 Installation
npm install smart-throttle-debounce
### ✅ Basic Usage
```javascript
import smartThrottleDebounce from 'smart-throttle-debounce';
// Fires immediately, then at most once every 300ms, and one final call after burst
const optimizedClickHandler = smartThrottleDebounce(() => {
console.log('Button clicked! (Optimized)');
}, 300);
document.getElementById('my-btn').addEventListener('click', optimizedClickHandler);
```html
<button id="my-btn">Click me</button>
## 🧠 Debounce Style Usage
```javascript
import smartThrottleDebounce from 'smart-throttle-debounce';
const searchInput = document.getElementById('search');
// This only fires *after* the user stops typing for 400ms
const handleSearch = smartThrottleDebounce((event) => {
console.log('Searching for:', event.target.value);
}, 400, { leading: false });
searchInput.addEventListener('input', handleSearch);
// Optional cleanup
// searchInput.removeEventListener('input', handleSearch);
// handleSearch.cancel();
```html
<input type="text" id="search" placeholder="Type to search..." />
## 💻 Scroll Example (Throttled + Final Update)
```javascript
window.addEventListener('scroll', smartThrottleDebounce(() => {
console.log('Scroll event handled efficiently!');
}, 200));
## API Reference
smartThrottleDebounce(fn, delay, [options])
Create an optimized, rate-limited function.
Parameters
Parameter Type Description Required Default
fn Function The function to wrap ✅ —
delay Number Delay time in milliseconds ✅ —
options Object Optional configuration ❌ { leading: true, trailing: true }
Options
leading (boolean) – Call on the first trigger. (default: true)
trailing (boolean) – Call after final event. (default: true)
Returns
A new wrapped function with intelligent throttle/debounce behavior.
Methods
.cancel() – Cancels any pending trailing execution.