Implement Debounce and Throttle

This exercise is commonly asked because it tests closures, timers, and function arguments.

Debounce

function debounce(fn, delay) {
  let timerId

  return function (...args) {
    clearTimeout(timerId)

    timerId = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

Use case:

const search = debounce((value) => {
  console.log('search', value)
}, 500)

Throttle

function throttle(fn, delay) {
  let waiting = false

  return function (...args) {
    if (waiting) return

    fn.apply(this, args)
    waiting = true

    setTimeout(() => {
      waiting = false
    }, delay)
  }
}

What interviewer checks