所有 JavaScript 应用都需要事件节流!事件节流结论

2025-06-07

所有 Javascript 应用程序都需要事件限制!!!

事件限制

结论

搜索栏中的每个按键是否都需要调用 API?如何优化滚动或调整大小事件?这类问题在 StackOverflow、GitHub 等平台上很常见。

只有当我们处于应用程序的优化阶段或我们真的陷入永无止境的 API 调用循环时,才会在 Google 上搜索这些问题。我是对的吗?

所有谷歌搜索都指向 Javascript 编程中的两个主要术语 -节流去抖

我们需要学习这些吗?当然!几乎所有 Web 应用程序都需要这些技术来优化性能。

简单地使用去抖动节流技术来限制函数执行的次数。

想象一下购物车应用中的搜索栏,当我们在搜索框中输入每个字母时,每次都会向服务器请求一次 API 调用。当我们查看浏览器中的网络部分时,
列表中似乎有许多待处理的 API 调用。

想想看?这对你的应用程序来说可以吗?真的不行!
那么问题来了——如何减少搜索栏中的 API 调用……是的!最后,你用 Google 搜索,所有搜索结果都重复说——使用节流和去抖动,伙计……!

事件限制

节流是一种技术,无论用户触发事件多少次,附加的功能都只会在固定的时间间隔执行。

实际上,节流是一种简单的技术,我们可以使用setTimeoutJavascript 中的函数来创建它。

setTimeout 函数

setTimeoutwebAPI浏览器提供的 JavaScript 调度函数。使用此功能,我们可以将事件或函数调用延迟一段时间。

语法是:

let timerId = setTimeout(callbackFunction, timeToDelay);

这里的callbackFunction定义了在timeToDelay时间段之后需要执行的代码。

setTimeout函数将返回一个timerId,它是一个正整数值,用于唯一标识通过调用创建的计时器setTimeout。该值可以传递给clearTimeouttimeout 函数。

请记住,timerId是节流的关键点

//Example of setTimeout
const showMessage = function() {
console.log('show this message after 2 seconds');
};

let timerId = setTimeout(showMessage, 2000); //the showMessage function will call after 2000 ms and show the message.

执行

节流将在一定间隔内触发附加的函数调用。对于下面给出的示例,无论是否实施节流,都会对滚动事件进行计数。

无节流

示例index.html文件为:

<head>
 <style>
        div {
            border: 1px  solid  black;
            width: 300px;
            height: 200px;
            overflow: scroll;
        }
    </style>  
</head>

<body>
    <div  id="div-body">
        <p style="background-color: red; height: 700px">This is line 1</p>
        <p style="background-color: blue; height: 700px">This is line 2</p>
        <p style="background-color: green; height: 700px">This is line 3</p>
        <p style="background-color: yellow; height: 700px">This is line 4</p>
    </div>

    <p>No of times event fired</p>
    <p id='show-api-call-count'></p>

    <script src= "script.js" />
</body>

该 JavaScriptscript.js文件是:


let timerId, eventCallCount;
const divBodyDom = document.getElementById('div-body');

divBodyDom.addEventListener('scroll', function() {
    const eventCallCountDom = document.getElementById('show-api-call-count');
    eventCallCount= eventCallCount|| 0;

    eventCallCount+= 1;
    eventCallCountDom.innerHTML = eventCallCount;

});

结果:
无节流

使用节流

示例index.html文件为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Throttling in Javascript</title>

    <style>
        div {
            border: 1px  solid  black;
            width: 300px;
            height: 200px;
            overflow: scroll;
        }
    </style>

</head>
<body>
    <div  id="div-body">
        <p style="background-color: red; height: 700px">This is line 1</p>
        <p style="background-color: blue; height: 700px">This is line 2</p>
        <p style="background-color: green; height: 700px">This is line 3</p>
        <p style="background-color: yellow; height: 700px">This is line 4</p>
    </div>

    <p>No of times event fired</p>
    <p id='show-api-call-count'></p>

    <p>No of times throttling executed the method</p>
    <p id="debounc-count"></p>

    <script src= "script.js" />
</body>
</html>

该 JavaScriptscript.js文件是:

let timerId, apiCallCount, throttlingDomCount;
const divBodyDom = document.getElementById('div-body');

function makeAPICall() {
    const throttlingDom = document.getElementById('debounc-count');

    throttlingDomCount = throttlingDomCount || 0;
    throttlingDomCount += 1;

    throttlingDom.innerHTML = throttlingDomCount;

}

function throttleFunction(func, delay) {
    if(timerId) {
        return;
    }

    timerId = setTimeout(function() {
        func();
        timerId = undefined;
    }, delay);
}

divBodyDom.addEventListener('scroll', function() {
    const apiCallCountDom = document.getElementById('show-api-call-count');
    apiCallCount = apiCallCount || 0;

    apiCallCount = parseInt(apiCallCount) + 1;
    apiCallCountDom.innerHTML = apiCallCount;

    throttleFunction(makeAPICall, 200);
});

结果:

事件限制

解释

这里throttle()函数将处理makeAPICall()并传递一个间隔值 200。
因此throttle()将安排以 200ms 的间隔触发makeAPICall()函数。

throttle()函数内部的重点是timerId

如果timerIdundefined,则setTimeout函数将触发并且timerId返回。

如果timerId有效,则表示有一个setTimeout函数尚未完成。对吗?所以它会直接返回,不执行任何操作。这意味着makeAPICall()函数只有在timerId被设置后才会执行。这只会在每个函数完成后才会发生setTimeout

通过将传递的延迟设置为函数的延迟参数,我们可以以200ms的固定间隔setTimeout执行makeAPICall()函数。

另外,不要忘记将timerId重置为undefined,这样只有下一次事件触发才会如我们所愿。

真的很简单..是吗?

结论

开发人员可以使用事件节流概念来控制时间间隔内的事件执行,例如窗口大小调整、重复按钮单击、快速搜索类型、鼠标移动事件等。

如何才能在事件完成后才执行某些操作?——使用Debouncing()。敬请期待我的下一篇博客!

文章来源:https://dev.to/jkjaikrishna/all-javascript-apps-need-event-throtdling-p88
PREV
使用 React 创建录音机
NEXT
在 React 应用中分离 API 层 - 实现可维护代码的 6 个步骤