迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中的 debounce() 函数

作者:迹忆客 最近更新:2024/03/18 浏览次数:

本文将教你如何利用 JavaScript debounce() 函数来提高应用程序的性能。


理解 JavaScript 中的术语 Debounce

JavaScript 使用去抖动技术来提高浏览器性能。去抖动是节流阀的相对物,它们都提高了在线应用程序的性能。

然而,它们在许多情况下被观察到。当我们只考虑最终状态时,就会使用去抖动。

例如,他们会延迟对预先输入的搜索结果的检索,直到用户完成输入。如果我们想控制所有中间状态的速度,最理想的工具是油门。


在 JavaScript 中使用 debounce() 函数

这是一个代码说明,可帮助你了解如何对函数进行去抖动:

function debounce(jss, timeout = 3000) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      jss.apply(this, args);
    }, timeout);
  };
}

function userInput() {
  console.log('Changing data');
}

const workonChange = debounce(() => userInput());

运行代码

那么,这里发生了什么?debounce() 是一个独特的函数,它执行两个功能:

  • 为计时器变量分配范围
  • 设置你的函数在特定时间运行

让我们看一下第一个带有文本输入的用例,看看它是如何工作的。

当访问者写下第一个字母并释放键(定时器)时,debounce() 函数最初使用 clearTimeout 重置定时器。此时不需要该步骤,因为没有任何计划。

函数 userInput() 预计将在 3000 毫秒(3 秒)内被调用。但是,如果访问者继续键入,每个基本版本都会重新触发 debounce() 函数。

每次调用都必须重置计时器,或者换句话说,取消任何早期的 userInput() 准备并重新安排它到一个新的时间——未来 3000 毫秒。只要访问者在 3000 毫秒内保持击键,这种情况就会继续。

因为之前的计划不会被清除,userInput() 将被调用。

输出:

你会看到当你输入 shivsetTimeout 方法会一直延迟(尽管调用了 userInput 函数)。当我们在打字时暂停三秒钟时,会打印出主要功能:Changing data

去抖动通过仅在设定的暂停时间后调用函数而不是在每次操作时调用函数来提高应用程序速度。但是,你不必自己完成此操作。

例如,Lodash 中提供了一个 debounce 功能。贡献者改进了 Lodash 等库,以改进 debounce 功能。

在本文中,我们已经讨论了什么是去抖动、它为什么有用以及如何在 JavaScript 中实现它。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便