什么是 JavaScript 中的 Debouncing?
Debouncing
Debouncing 只不过是减少不必要的耗时计算,从而提高浏览器性能。在某些情况下,某些功能需要更多时间来执行某些操作。例如,以电子商务网站中的 搜索栏 为例。
汇报
假设用户想要获得 Tutorix 学习套件 。他在搜索栏中输入产品的每个字符。输入每个字符后,浏览器和服务器之间都会发生 Api 调用,以获取所需的产品。由于他想要"Tutorix 学习套件",因此用户必须从浏览器到服务器进行 17 次 Api 调用。想象一下这样的场景:数百万人通过调用数十亿个 Api 进行相同的搜索。因此,一次调用数十亿个 Api 肯定会导致 浏览器性能变慢。为了减少这个缺点,Debouncing 应运而生。
在这种情况下,Debouncing 将在两次击键之间设置一个时间间隔,假设为 2 秒。如果两次击键之间的时间超过 2 秒,则只会发生 Api 调用。在这 2 秒内,用户可能会输入至少一些字符,从而减少对这些字符的 Api 调用。由于 Api 调用减少,浏览器性能将得到提高。必须注意,Debounce 函数会针对每次按键进行更新。
示例摘要
在下面的示例中,一个按钮被附加到调用 debounce 函数的 事件监听器。Debounce 函数提供 2 个参数,一个是函数,另一个是数字(时间)。声明了一个 Timer,顾名思义,它会在特定时间后调用 debounce 函数。
单击 debounce 按钮后,会打开一个警告框并显示一条消息。该函数每次更新,这意味着如果在延迟时间(2 秒)之前单击按钮,则将清除初始计时器并启动新的计时器。要完成此任务,请使用 clearTimeOut() 函数。
示例
<html> <body> <input type = "button" id="debounce" value = "Debounce"> <script> var button = document.getElementById("debounce"); var debounce = (func, delay) => { let Timer return function() { const context = this const args = arguments clearTimeout(Timer)Timer= setTimeout(() => func.apply(context, args), delay) } } button.addEventListener('click', debounce(function() { alert("Hello
No matter how many times you" + "click the debounce button, I get " +"executed once every 2 seconds!!")}, 2000)); </script> </body> </html>
执行上述函数后,将显示以下按钮
单击按钮并等待 2 秒后,将显示以下警告框作为输出。