Home >Web Front-end >JS Tutorial >How to implement function anti-shake and throttling in js

How to implement function anti-shake and throttling in js

藏色散人
藏色散人forward
2020-05-24 13:34:492336browse

Conceptual understanding

Anti-shake: Execute the callback n seconds after the event is triggered. If it is triggered again within these n seconds, restart the time.

Throttling: It is stipulated that the function can only be triggered once within a unit time. If the function is triggered multiple times within this unit time, only one will take effect.

Related recommendations: "javascript Advanced Tutorial"

The difference between js function anti-shake and throttling:

Function anti-shake Jittering is executed only once within a certain period of time, while function throttling is executed at intervals.

Personal pitfalls

1. After understanding the concepts of function anti-shake and function throttling, using closures to implement function anti-shake and throttling did not take into account For throttling, if the user has finished inputting before the next request, but will not make another request at this time, it will cause the last entered text to be changed by other events without sending a request, that is, a request is missed, so a setTimeout function needs to be added. And every time when preparing a request, set a flag, that is, whether the request has been sent. If the request is sent in a normal cycle, change it to true. Otherwise, it is false. Use setTimeout. Let setTimeout be slightly longer than the remaining events and take priority. Throttle timer request;

2. If you use arrow functions, you do not need to save this.

Code implementation

 <div>
    <div>
        <input type="text" id="unDebounce">
    </div>
    <div>
        <input type="text" id="debounce">
    </div>
    <div>
        <input type="text" id="throttle">
    </div>
</div>
rrree

The above is the detailed content of How to implement function anti-shake and throttling in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete