Debouncing in JavaScript

const debounce = (func, delay) => {
  let inDebounce
  return function() {
    const context = this
    const args = arguments
    clearTimeout(inDebounce)
    inDebounce = setTimeout(() => func.apply(context, args), delay)
  }
}

Debouncing limits the rate at which a function gets invoked, which improve browser performance.

We are passing a function(func) and a delay(delay) into the debounce function. inDebounce is a variable that we use to track the delay period.

Quick logic: If we are invoking for the first time, our function will execute at the end of our delay. If we invoke and then invoke again before the end of our delay, the delay restarts

要查看或添加评论,请登录

Raman Verma的更多文章

  • Memoization in JavaScript

    Memoization in JavaScript

    Memoization is the programmatic practice of making long recursive/iterative functions run much faster. Memoization is…

社区洞察

其他会员也浏览了