Debounce Function

Utility function to debounce function calls, limiting function execution rate

javascript (ES2015) 2025-11-12 utility performance async throttle

Description

A debounce function that delays function execution until after a specified wait time has elapsed since the last invocation. Useful for rate-limiting expensive operations like API calls, search inputs, or resize handlers.

Features

  • Configurable delay time
  • Optional immediate execution
  • Cancellation support

Code

RAW
function debounce(func, wait, immediate = false) {  let timeout;    return function executedFunction(...args) {    const later = () => {      timeout = null;      if (!immediate) func(...args);    };        const callNow = immediate && !timeout;    clearTimeout(timeout);    timeout = setTimeout(later, wait);        if (callNow) func(...args);  };}module.exports = debounce;
RAW
const debounce = require('./debounce');// Debounce search inputconst searchInput = document.getElementById('search');const debouncedSearch = debounce((query) => {  console.log('Searching for:', query);  // API call here}, 300);searchInput.addEventListener('input', (e) => {  debouncedSearch(e.target.value);});// Immediate execution variantconst debouncedResize = debounce(() => {  console.log('Window resized');}, 300, true);window.addEventListener('resize', debouncedResize);

Comments

No comments yet. Be the first to comment!