去抖动和 Web 性能

2025-06-04

去抖动和 Web 性能

当你制作可扩展的 Web 产品并参加 JavaScript 面试时,去抖动非常重要。

介绍

去抖动是 Web 开发人员经常使用的提高浏览器性能的重要实践。

防抖方法在调用时不会执行。相反,它们会等待一段预定的时间后再执行。如果再次调用相同的方法,则会取消前一个方法并重新启动计时器。

示例:
考虑此示例中,与按钮关联的函数将在按钮按下后 2 秒被调用。无论您连续按下多少次,它都只会执行一次。

让我们理解代码

function debounce(func, wait, immediate) {
  var timeout;

  return function executedFunction() {
    var context = this;
    var args = arguments;

    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    var callNow = immediate && !timeout;

    clearTimeout(timeout);

    timeout = setTimeout(later, wait);

    if (callNow) func.apply(context, args);
  };
};
Enter fullscreen mode Exit fullscreen mode

这里的 debounce 函数有三个参数

  1. 需要执行的功能。
  2. 等待时间。
  3. 您是否想立即调用此功能(可选)。

我们也可以很容易地在 React 中实现这一点lodash

假设有人正在构建一个搜索应用程序,每次击键后都会进行一次 api 调用。考虑这个例子,借助去抖动,您可以直观地看到触发事件之间的差异。

让我们理解代码

 onSearchItemWithDebounce = debounce((query) => {
    this.setState({
      queryWithDebounce: query
    }, () => {
      //Do Stuff after state is updated.
      console.log('search with Debounce: ', this.state.queryWithDebounce);
    })
    this.setState({eventsFiredDebounce : this.state.eventsFiredDebounce+ 1})
  }, WAIT_TIME);
Enter fullscreen mode Exit fullscreen mode

**Note : debounce is imported from lodash**

感谢 Bearing,
我将在即将发布的文章中撰写文章解释 React 提供的每个钩子,请关注以保持联系。

文章来源:https://dev.to/amankumarsingh01/debouncing-and-web-performance-2dfc
PREV
提高 Web 性能和 Lighthouse 性能结果
NEXT
使用 React Router 优化单页应用程序