@manufosela/debounce-throttle
Debounce and throttle utility functions with leading, trailing, and maxWait options
Demo code (CodePen-ready HTML, CSS, JS)
HTML (html)
<div class="top-links">
<a href="https://manufosela.dev/utils/">Utils catalog</a>
<a href="https://manufosela.dev/">Main catalog</a>
<a href="https://github.com/manufosela/utils/tree/main/packages/debounce-throttle">Source</a>
</div>
<demo-theme-toggle></demo-theme-toggle>
<h1>debounce-throttle</h1>
<p class="subtitle">Debounce, throttle, and rate-limit utilities in action.</p>
<div class="section">
<h2>Quick usage</h2>
<pre class="code-block"><code>import { debounce, throttle } from '@manufosela/debounce-throttle';
const debounced = debounce(onInput, 300);
const throttled = throttle(onScroll, 200);
</code></pre>
</div>
<!-- Debounce Demo -->
<div class="section">
<h2>Debounce - Search Input</h2>
<p style="color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1rem;">
Type in the input and see how debounce delays the API call until you stop typing.
</p>
<div class="demo-row">
<div class="demo-controls">
<label>Delay: <span id="debounceDelayValue">300</span>ms</label>
<input type="range" id="debounceDelay" min="100" max="1000" value="300" step="100">
<input type="text" id="searchInput" placeholder="Type to search...">
</div>
<div class="event-log" id="debounceLog"></div>
</div>
<div class="stats">
<div class="stat">
<div class="stat-value raw" id="debounceRawCount">0</div>
<div class="stat-label">Keystrokes</div>
</div>
<div class="stat">
<div class="stat-value processed" id="debounceProcessedCount">0</div>
<div class="stat-label">API Calls</div>
</div>
<div class="stat">
<div class="stat-value" id="debounceSavings">0%</div>
<div class="stat-label">Calls Saved</div>
</div>
</div>
<pre class="code-block"><code>import { debounce } from '@manufosela/debounce-throttle';
const debouncedSearch = debounce((value) => {
fetch(`/api/search?q=${value}`);
}, 300);
input.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});
</code></pre>
</div>
<!-- Throttle Demo -->
<div class="section">
<h2>Throttle - Scroll Handler</h2>
<p style="color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1rem;">
Scroll inside the box and see how throttle limits the handler calls.
</p>
<div class="demo-row">
<div class="demo-controls">
<label>Limit: <span id="throttleLimitValue">100</span>ms</label>
<input type="range" id="throttleLimit" min="50" max="500" value="100" step="50">
<div class="scroll-area" id="scrollArea">
<div class="scroll-content"></div>
</div>
</div>
<div class="event-log" id="throttleLog"></div>
</div>
<div class="stats">
<div class="stat">
<div class="stat-value raw" id="throttleRawCount">0</div>
<div class="stat-label">Scroll Events</div>
</div>
<div class="stat">
<div class="stat-value processed" id="throttleProcessedCount">0</div>
<div class="stat-label">Handler Calls</div>
</div>
<div class="stat">
<div class="stat-value" id="throttleSavings">0%</div>
<div class="stat-label">Calls Saved</div>
</div>
</div>
<pre class="code-block"><code>import { throttle } from '@manufosela/debounce-throttle';
const onScroll = throttle(() => {
console.log('scroll tick');
}, 100);
scrollArea.addEventListener('scroll', onScroll);
</code></pre>
</div>
<!-- Once Demo -->
<div class="section">
<h2>Once - Single Initialization</h2>
<p style="color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1rem;">
Click the button multiple times - the function only executes once.
</p>
<div class="button-group">
<button id="onceButton">Initialize (click multiple times)</button>
<button id="onceReset">Reset</button>
</div>
<div class="event-log" id="onceLog" style="height: 100px; margin-top: 1rem;"></div>
<pre class="code-block"><code>import { once } from '@manufosela/debounce-throttle';
const initOnce = once(() => {
initWidget();
});
button.addEventListener('click', initOnce);
</code></pre>
</div>
<!-- Rate Limit Demo -->
<div class="section">
<h2>Rate Limit - API Calls</h2>
<p style="color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1rem;">
Limited to 5 calls per 3 seconds. Click rapidly to see rate limiting in action.
</p>
<div class="button-group">
<button id="rateLimitButton">Call API</button>
</div>
<div class="event-log" id="rateLimitLog" style="height: 150px; margin-top: 1rem;"></div>
<div class="stats">
<div class="stat">
<div class="stat-value raw" id="rateLimitAttempts">0</div>
<div class="stat-label">Attempts</div>
</div>
<div class="stat">
<div class="stat-value processed" id="rateLimitSuccess">0</div>
<div class="stat-label">Successful</div>
</div>
<div class="stat">
<div class="stat-value" id="rateLimitBlocked">0</div>
<div class="stat-label">Blocked</div>
</div>
</div>
<pre class="code-block"><code>import { rateLimit } from '@manufosela/debounce-throttle';
const limitedCall = rateLimit(() => {
callApi();
}, 5, 3000);
button.addEventListener('click', limitedCall);
</code></pre>
</div> CSS (css)
:root {
--bg: #0c0f14;
--bg-elevated: #141923;
--bg-panel: #171d28;
--border: #262f3f;
--text: #f4f6fb;
--text-muted: #a7b0c2;
--text-dim: #7d879b;
--accent: #ff8a3d;
--accent-strong: #ff6a00;
--accent-soft: rgba(255, 138, 61, 0.16);
--shadow: 0 20px 50px rgba(5, 8, 14, 0.45);
--radius-lg: 22px;
--radius-md: 14px;
--radius-sm: 10px;
--max-width: 1160px;
}
* {
box-sizing: border-box;
}
h1 {
color: var(--accent);
margin-bottom: 0.5rem;
}
.subtitle {
color: var(--text-muted);
margin-bottom: 2rem;
}
.top-links {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
margin-bottom: 1rem;
}
.top-links a {
font-size: 0.8rem;
color: var(--text-muted);
text-decoration: none;
border: 1px solid var(--border);
padding: 0.35rem 0.75rem;
border-radius: 999px;
}
.section {
background: var(--bg-elevated);
border-radius: 8px;
padding: 1.5rem;
margin-bottom: 1.5rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.section h2 {
margin: 0 0 1rem;
color: var(--text);
font-size: 1.25rem;
}
.demo-row {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
align-items: start;
margin-bottom: 1rem;
}
.demo-controls {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.demo-controls label {
font-size: 0.875rem;
color: var(--text-muted);
}
.demo-controls input[type="range"] {
width: 100%;
}
.demo-controls input[type="text"] {
padding: 0.5rem;
border: 1px solid var(--border);
border-radius: 4px;
width: 100%;
}
.event-log {
background: var(--bg-panel);
color: var(--text);
border-radius: 4px;
padding: 1rem;
font-family: monospace;
font-size: 0.875rem;
height: 150px;
overflow-y: auto;
}
.event-log .raw {
color: #f14c4c;
}
.event-log .processed {
color: #4ec9b0;
}
.event-log .time {
color: var(--text-dim);
}
.stats {
display: flex;
gap: 2rem;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--border);
}
.stat {
text-align: center;
}
.stat-value {
font-size: 2rem;
font-weight: bold;
color: var(--text);
}
.stat-label {
font-size: 0.75rem;
color: var(--text-muted);
text-transform: uppercase;
}
.stat-value.raw {
color: #f14c4c;
}
.stat-value.processed {
color: #4ec9b0;
}
button {
padding: 0.5rem 1rem;
background: var(--accent);
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 0.875rem;
}
button:hover {
background: var(--accent-strong);
}
.button-group {
display: flex;
gap: 0.5rem;
margin-top: 0.5rem;
}
.scroll-area {
height: 100px;
overflow-y: auto;
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 4px;
padding: 1rem;
}
.scroll-content {
height: 500px;
background: linear-gradient(to bottom, var(--bg-panel), #1f2937, #273449, #2e3c55, #334155);
}
.resize-area {
resize: both;
overflow: auto;
min-width: 200px;
min-height: 80px;
max-width: 100%;
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 4px;
padding: 1rem;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted);
}
.code-block {
background: #0b0f1a;
border: 1px solid #2b3247;
border-radius: 8px;
padding: 12px;
color: #d6d9e6;
font-family: "JetBrains Mono", "Courier New", monospace;
font-size: 0.85rem;
white-space: pre-wrap;
word-break: break-word;
}
:root {
--bg: #0f1117;
--bg-2: #151a26;
--bg-spot-1: #1a2136;
--bg-spot-2: #1d1b34;
--card: #1c2233;
--text: #f3f6ff;
--muted: #b8c0d9;
--line: #2b3247;
--accent: #ffb000;
--accent-2: #00d0ff;
--surface: #0b0f1a;
--code-bg: #0b0f1a;
--code-text: #d6d9e6;
}
:root.light {
--bg: #f5f5f7;
--bg-2: #ffffff;
--bg-spot-1: #f8e9d0;
--bg-spot-2: #e8eef8;
--card: #ffffff;
--text: #1d1d1f;
--muted: #6b7280;
--line: #e5e7eb;
--accent: #ffb000;
--accent-2: #00a7d6;
--surface: #f3f4f6;
--code-bg: #111827;
--code-text: #f9fafb;
}
:root.dark {
--bg: #0f1117;
--bg-2: #151a26;
--bg-spot-1: #1a2136;
--bg-spot-2: #1d1b34;
--card: #1c2233;
--text: #f3f6ff;
--muted: #b8c0d9;
--line: #2b3247;
--accent: #ffb000;
--accent-2: #00d0ff;
--surface: #0b0f1a;
--code-bg: #0b0f1a;
--code-text: #d6d9e6;
}
h1 {
color: var(--accent) !important;
}
.top-links a,
.topbar a {
color: var(--muted) !important;
border-color: var(--line) !important;
}
.top-links a:hover,
.topbar a:hover {
color: var(--text) !important;
}
.card,
.section,
.demo-section,
.panel {
background: var(--card) !important;
border-color: var(--line) !important;
color: var(--text) !important;
}
.code-block,
pre,
code,
.output,
.current-url,
.event-log,
.result-card,
.log {
background: var(--code-bg) !important;
color: var(--code-text) !important;
border-color: var(--line) !important;
}
input,
select,
textarea {
background: var(--surface) !important;
color: var(--text) !important;
border-color: var(--line) !important;
}
button {
background: linear-gradient(120deg, var(--accent), #ff6a00) !important;
color: #111 !important;
}
footer {
color: var(--muted) !important;
}
footer a {
color: var(--text) !important;
} JS (js)
import { debounce, throttle, once, rateLimit } from "https://esm.sh/@manufosela/debounce-throttle";
// Helper to format time
function formatTime() {
const now = new Date();
return `${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}.${now.getMilliseconds().toString().padStart(3, '0')}`;
}
// Helper to add log entry
function addLog(logId, message, type = 'raw') {
const log = document.getElementById(logId);
const entry = document.createElement('div');
entry.innerHTML = `<span class="time">[${formatTime()}]</span> <span class="${type}">${message}</span>`;
log.appendChild(entry);
log.scrollTop = log.scrollHeight;
}
// ============ Debounce Demo ============
let debounceRawCount = 0;
let debounceProcessedCount = 0;
let currentDebouncedSearch;
function createDebouncedSearch(delay) {
return debounce((value) => {
debounceProcessedCount++;
document.getElementById('debounceProcessedCount').textContent = debounceProcessedCount;
addLog('debounceLog', `API call with: "${value}"`, 'processed');
updateDebounceSavings();
}, delay);
}
currentDebouncedSearch = createDebouncedSearch(300);
document.getElementById('searchInput').addEventListener('input', (e) => {
debounceRawCount++;
document.getElementById('debounceRawCount').textContent = debounceRawCount;
addLog('debounceLog', `Keystroke: "${e.target.value}"`, 'raw');
currentDebouncedSearch(e.target.value);
updateDebounceSavings();
});
document.getElementById('debounceDelay').addEventListener('input', (e) => {
document.getElementById('debounceDelayValue').textContent = e.target.value;
currentDebouncedSearch.cancel();
currentDebouncedSearch = createDebouncedSearch(parseInt(e.target.value));
});
function updateDebounceSavings() {
const savings = debounceRawCount > 0
? Math.round((1 - debounceProcessedCount / debounceRawCount) * 100)
: 0;
document.getElementById('debounceSavings').textContent = `${savings}%`;
}
// ============ Throttle Demo ============
let throttleRawCount = 0;
let throttleProcessedCount = 0;
let currentThrottledScroll;
function createThrottledScroll(limit) {
return throttle((scrollTop) => {
throttleProcessedCount++;
document.getElementById('throttleProcessedCount').textContent = throttleProcessedCount;
addLog('throttleLog', `Handler: scrollTop = ${scrollTop}px`, 'processed');
updateThrottleSavings();
}, limit);
}
currentThrottledScroll = createThrottledScroll(100);
document.getElementById('scrollArea').addEventListener('scroll', (e) => {
throttleRawCount++;
document.getElementById('throttleRawCount').textContent = throttleRawCount;
addLog('throttleLog', `Scroll event: ${e.target.scrollTop}px`, 'raw');
currentThrottledScroll(e.target.scrollTop);
updateThrottleSavings();
});
document.getElementById('throttleLimit').addEventListener('input', (e) => {
document.getElementById('throttleLimitValue').textContent = e.target.value;
currentThrottledScroll.cancel();
currentThrottledScroll = createThrottledScroll(parseInt(e.target.value));
});
function updateThrottleSavings() {
const savings = throttleRawCount > 0
? Math.round((1 - throttleProcessedCount / throttleRawCount) * 100)
: 0;
document.getElementById('throttleSavings').textContent = `${savings}%`;
}
// ============ Once Demo ============
let createOnceFunction;
function setupOnceDemo() {
createOnceFunction = once(() => {
addLog('onceLog', 'Function executed! This only happens once.', 'processed');
return 'initialized';
});
}
setupOnceDemo();
document.getElementById('onceButton').addEventListener('click', () => {
addLog('onceLog', 'Button clicked', 'raw');
const result = createOnceFunction();
if (result) {
addLog('onceLog', `Returned: "${result}"`, 'processed');
}
});
document.getElementById('onceReset').addEventListener('click', () => {
document.getElementById('onceLog').innerHTML = '';
setupOnceDemo();
addLog('onceLog', 'Demo reset', 'processed');
});
// ============ Rate Limit Demo ============
let rateLimitAttempts = 0;
let rateLimitSuccess = 0;
let rateLimitBlocked = 0;
const rateLimitedApi = rateLimit(() => {
rateLimitSuccess++;
document.getElementById('rateLimitSuccess').textContent = rateLimitSuccess;
addLog('rateLimitLog', 'API call successful', 'processed');
return true;
}, 5, 3000);
document.getElementById('rateLimitButton').addEventListener('click', () => {
rateLimitAttempts++;
document.getElementById('rateLimitAttempts').textContent = rateLimitAttempts;
addLog('rateLimitLog', 'Attempting API call...', 'raw');
const result = rateLimitedApi();
if (result === undefined) {
rateLimitBlocked++;
document.getElementById('rateLimitBlocked').textContent = rateLimitBlocked;
addLog('rateLimitLog', 'BLOCKED - Rate limit exceeded (5 per 3s)', 'raw');
}
});
class DemoThemeToggle extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.handleClick = this.handleClick.bind(this);
}
connectedCallback() {
const saved = localStorage.getItem('utils-demo-theme');
document.documentElement.classList.remove('dark');
document.documentElement.classList.toggle('light', saved === 'light');
this.render();
}
render() {
const isLight = document.documentElement.classList.contains('light');
this.shadowRoot.innerHTML = `
<style>
:host {
display: inline-flex;
}
.toggle {
display: inline-flex;
align-items: center;
border: 1px solid var(--line);
border-radius: 999px;
overflow: hidden;
background: var(--surface);
}
button {
border: none;
background: transparent;
color: var(--muted);
padding: 6px 12px;
font-size: 0.8rem;
cursor: pointer;
font-family: "Space Grotesk", "Trebuchet MS", Arial, sans-serif;
}
button.active {
background: linear-gradient(120deg, var(--accent), #ff6a00);
color: #111;
font-weight: 600;
}
</style>
<div class="toggle" role="group" aria-label="Theme toggle">
<button class="${isLight ? 'active' : ''}" data-theme="light">Light</button>
<button class="${isLight ? '' : 'active'}" data-theme="dark">Dark</button>
</div>
`;
this.shadowRoot.querySelectorAll('button').forEach((btn) => {
btn.addEventListener('click', this.handleClick);
});
}
handleClick(event) {
const theme = event.currentTarget.dataset.theme;
const isLight = theme === 'light';
document.documentElement.classList.toggle('light', isLight);
document.documentElement.classList.remove('dark');
localStorage.setItem('utils-demo-theme', isLight ? 'light' : 'dark');
this.render();
}
}
customElements.define('demo-theme-toggle', DemoThemeToggle);