Skip to main content

Performance-patterns

Debounce vs. Throttle

  • Both debounce and throttle are techniques for controlling how often a function is executed, especially during frequent events such as typing, scrolling, or resizing.

Debounce

Definition

  • Debouncing delays the execution of a function until a specified amount of time has passed since the last call.
  • Use Cases
    • Search autocomplete: Only fetch results after the user stops typing.
    • Form validation: Validate after the user finishes typing.
    • Auto-save drafts: Save after the user pauses editing.

Implementation

function debounce(fn, delay) {
let timeoutId

return function (...args) {
// Clear any existing timer
clearTimeout(timeoutId)

// Set a new timer
timeoutId = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}

Usage

// Only search after the user stops typing for 300ms
const debouncedSearch = debounce((query) => {
console.log("Searching for:", query.target.value)
fetchSearchResults(query)
}, 300)

input.addEventListener("input", debouncedSearch)

Throttle

Definition

  • Throttling ensures that a function executes at most once within a specified time interval.
  • Unlike debouncing, throttling guarantees regular execution during continuous events. it does not wait for the events to stop.
  • Example
    • Instead of animating a div on every scroll event, move the div every 100 ms while scrolling.
    • While an action is ongoing, perform the task every n milliseconds instead of on every event.
  • Use Cases
    • Scroll position tracking: Need regular position updates.
    • Infinite scroll: Check proximity to the bottom regularly.
    • Mouse move tooltips: Update position smoothly.
    • Live preview: Show changes without lag.

Implementation

function throttle(fn, interval) {
let lastTime = 0

return function (...args) {
const now = Date.now()

// Only execute if enough time has passed
if (now - lastTime >= interval) {
lastTime = now
fn.apply(this, args)
}
}
}

Usage

// Update position at most every 100ms while scrolling
const throttledScroll = throttle(() => {
console.log("Scroll position:", window.scrollY)
updateScrollIndicator()
}, 100)

window.addEventListener("scroll", throttledScroll)

Throttle vs. requestAnimationFrame

  • Use requestAnimationFrame for:
    • Animating DOM elements
    • Parallax effects
  • Use Throttle for:
    • Rate-limiting API calls
    • Analytics event tracking