JavaScript - Throttle & Debounce

Overview

Estimated time: 10–15 minutes

Throttle and debounce are techniques to control how often a function is executed, especially in response to high-frequency events like scrolling, resizing, or typing.

Learning Objectives

  • Understand the difference between throttling and debouncing
  • Implement throttle and debounce in JavaScript
  • Know when to use each technique

Prerequisites

Throttle

Throttle ensures a function is called at most once every N milliseconds.

function throttle(fn, delay) {
  let last = 0;
  return function(...args) {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn.apply(this, args);
    }
  };
}

Debounce

Debounce delays function execution until after N milliseconds have passed since the last call.

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

Use Cases

  • Throttle: window resize, scroll events, API polling
  • Debounce: search input, auto-save, validation

Common Pitfalls

  • Using debounce when throttle is needed (and vice versa)
  • Not clearing timers in debounce

Summary

Throttle and debounce are essential for optimizing event-driven code and improving user experience.