JAVASCRIPT

Debounce DOM Event Listeners for Performance

Optimize browser performance by debouncing frequently firing DOM events like resize or scroll, ensuring event handlers execute only after a pause.

<style>
  body { margin: 0; padding: 0; }
  #output { 
    position: fixed; top: 10px; left: 10px; 
    background: rgba(0,0,0,0.7); color: white; 
    padding: 10px; font-family: monospace;
  }
</style>

<div id="output">Resize count: 0</div>

<script>
  let resizeCount = 0;
  const outputDiv = document.getElementById('output');

  // Debounce function
  function debounce(func, delay) {
    let timeout;
    return function(...args) {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(context, args), delay);
    };
  }

  // Event handler that will be debounced
  const handleResize = () => {
    resizeCount++;
    outputDiv.textContent = `Resize count: ${resizeCount} (Window size: ${window.innerWidth}x${window.innerHeight})`;
    console.log('Window resized!', new Date().toLocaleTimeString());
  };

  // Attach the debounced event listener
  window.addEventListener('resize', debounce(handleResize, 200));
</script>
How it works: Debouncing is a control technique that ensures a function, especially one attached to a DOM event that fires frequently (like `resize`, `scroll`, `mousemove`), is not called too often. Instead, the function will only execute after a specified delay has passed since the *last* time the event was triggered. This prevents performance issues by reducing unnecessary executions of expensive operations. The snippet provides a generic `debounce` utility function and demonstrates its application to the `window.resize` event.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs