Skip to content

Instantly share code, notes, and snippets.

@RussellJapheth
Created February 10, 2026 07:07
Show Gist options
  • Select an option

  • Save RussellJapheth/4272b18eb4742c41c42a5c3218c4bce0 to your computer and use it in GitHub Desktop.

Select an option

Save RussellJapheth/4272b18eb4742c41c42a5c3218c4bce0 to your computer and use it in GitHub Desktop.
Debounce a function in javascript
/**
* Creates a debounced version of a function that delays execution until after
* 'delay' milliseconds have elapsed since the last time it was invoked.
*
* @param {Function} fn - The function to execute.
* @param {number} [delay=300] - The delay in milliseconds.
* @returns {Function} - The debounced function with a .cancel() method.
*/
export function debounce(fn, delay = 300) {
let timeoutId = null;
function debounced(...args) {
// If a timer is already running, clear it to "reset" the clock
if (timeoutId) {
clearTimeout(timeoutId);
}
// Schedule the function execution
timeoutId = setTimeout(() => {
// Execute fn with the correct context ('this') and arguments
fn.apply(this, args);
// Reset timeoutId once executed
timeoutId = null;
}, delay);
}
/**
* Allows manual cancellation of the pending execution.
*/
debounced.cancel = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
return debounced;
}
import { debounce } from './debounce.js';
// 1. The function we want to limit
function performSearch(query) {
console.log(`Searching API for: ${query}...`);
// This is where your fetch() logic would go
}
// 2. Wrap it in a debounce (wait 500ms after the last keystroke)
const debouncedSearch = debounce((event) => {
const query = event.target.value;
if (query.length > 2) {
performSearch(query);
}
}, 500);
// 3. Attach it to an input field
const searchInput = document.querySelector('#search-bar');
searchInput.addEventListener('input', debouncedSearch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment