Anti shake:
- The callback is executed n seconds after the event is triggered. If it is triggered again within these n seconds, the timing will be re timed.
- The action is delayed. After the event is triggered, the action will be executed in n seconds.
- For example, if you want to search a string, based on performance considerations, you can't send a search request every time you enter a character. At this time, js anti shake can be used. After the user stops inputting for a period of time (e.g. 10ms), we send a request.
Throttling:
- It is specified that the function can only be triggered once in a unit time. If the function is triggered multiple times in this unit time, only one will take effect.
- Actions are performed periodically. Only one action is executed within a fixed time. If a new event is triggered, it will not be executed.
- For example, in the process of user input, query the relevant string every 10ms.
Difference between anti shake and throttling:
- It is also a waiting period of 2s. Anti shake is to re time as long as the trigger interval is within 2s;
- Throttling is that 2s gives an opportunity to execute the time function, and it can also set whether the first and last operations are executed.
Selection of anti chattering and throttling strategies:
- If the event trigger is high frequency but there is a pause, you can choose anti shake;
- When events are triggered continuously and frequently, throttling can only be selected, because anti chattering may cause the action to be executed only once and the interface to jump.
1. Anti shake
1.1 situation where anti shake is not used
1) Take the keyup event of the input box as an example. As you can see, console events are executed multiple times per second.
Solution: js anti shake can be used to trigger judgment after the user stops inputting for a period of time (e.g. 500ms)
1.2 after using anti shake
It can be seen that if the user keeps inputting, the console event will not be triggered. This is because the keyup event is triggered again within the specified 500ms time interval, and the timer starts timing again. When the user does not input within 500ms interval, an event will be triggered. It is suitable for real-time judging whether the content entered by the user (such as email and telephone) meets the format requirements and other scenarios.
1.3 realization of anti shake
Idea: cancel the previous delayed call method every time the event is triggered.
When the user triggers the click event delay ms, we send the request. Therefore, we use a timer to save the user's operation every time, and then clear the last timer every time the click event is triggered within the delay time, so as to ensure that only one request is sent after the delay of MS.
//1. Realize the anti shake function. After triggering the event delay ms, execute the action fn function debounce(fn,delay){ let timeout = null; //1) Store the return value of the timer to facilitate clearing the timer return function(){ clearTimeout(timeout); // 2) Each time an event is triggered, the timer of the previous event is cleared timeout = setTimeout(() => { fn.apply(this, arguments); // 3) Execute action fn after delay Ms. this points to the div that triggered the event },delay) } } // Define action function sayHi(){ console.log("Anti shake successful"); } // Trigger the click event of box (add a click event for box, and execute the function returned by debounce when clicking) let box = document.getElementById('box'); box.addEventListener('click', debounce(sayHi, 500));
<div id="box" style="height: 100px; width: 100px; background: cadetblue;"></div>
Click once and print "anti shake succeeded" after 500ms.
When clicking for many times, the timing starts at the end of the last click, and the "anti shake success" is printed after 500ms.
2. Throttling
2.1 usage scenarios of throttling
The following situations need to be solved by throttling:
1) resize and scroll events of window
For example, scroll to the bottom of the page to load more. A little scrolling will trigger n more scroll events. If you judge whether you have scrolled to the bottom of the page every time you trigger the scroll event, it will undoubtedly cause a waste of resources. At this time, if js throttling is used, the judgment is made every certain time (such as 500ms), and the judgment can only be triggered once during the interval, which saves resources and will not affect the user experience.
2) Click the mouse repeatedly to trigger MouseDown (only triggered once per unit time)
For example, click the submit button to submit the form information. If you accidentally click it for several times in succession, you will submit it for many times.
Solution: use js throttling to execute regularly, and submit only once in a fixed cycle.
2.2 realization of throttling
High frequency events are triggered, but they will only be executed once in n seconds, so throttling will reduce the execution frequency of the function
Idea: each time an event is triggered, judge whether there is a delay function waiting to be executed
//1. Realize the throttling function. Perform the action once every delay ms function throttle(fn, delay){ var runFlag = false; //1) Judge whether there is a delay function waiting to be executed. false: there are no functions waiting to be executed return function(){ if(runFlag) { //2) There are waiting functions before execution. Since it is executed only once in the delay, it is returned directly. return false; }; runFlag = true; //3) The current function is waiting to be executed setTimeout(() => { fn.apply(this, arguments); //4) After the delay, execute action fn. this points to the div being clicked runFlag = false; //5) The current function has finished executing. There are no functions waiting to be executed }, delay) } } // Define action function sayHi(){ console.log("Throttling success"); } // Trigger the click event of box (add a click event for box, and execute the function returned by throttle when clicking) let box = document.getElementById('box'); box.addEventListener('click', throttle(sayHi, 1000));
In the delay cycle, no matter how many clicks are made, only the action triggered at the first click will be executed after the delay time