Original link: juejin.cn/post/684490…
The introduction
Recently, WHEN doing business requirements, I encountered an optimization problem: Under the condition of weak network, after a series of operations, users would click to pay for several times, so they would set up multiple cash registers, which was not a good experience. Finally, with the help of colleagues, I solved this problem by making anti-shaking treatment for click-to-pay operation, which aroused my interest in learning anti-shaking and throttling common in JS
Image stabilization
- Concept: For consecutive events that occur in a short period of time (scroll,resize,click,,,,,), the event handler will perform only one operation within a certain period of time, that is, multiple operations will be combined into one operation.
- Implementation: Set a delayed call method each time the event is triggered, and cancel the previous delayed call method – using setTimeout and mandatory package implementation
Let’s look at the code:
Const debundle = (func, delay) => {let timeout = null; const debundleHandle = function () { const context = this const args = arguments; clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args) }, delay); } return debundleHandle }Copy the code
const elementDebounce = document.getElementById("debounce") elementDebounce && elementDebounce.addEventListener('click', debundle( () => { debounceBtnClick(executetime++) }, 1000 ) )Copy the code
Test demo repeatedly in a short period of time to frequently click a counter to increase the button, calculate the number of times the event handler function is executed, observe the effect of shaking.
As you can see, when the click event continues to fire, the event handler is called only once after the click has stopped for 1000 milliseconds, meaning that the event handler never executes during the click event.
However, there is a disadvantage of anti – shake. If the event is triggered repeatedly within a specified time, the handler function will be delayed continuously, which can be used in practical applications.
The throttle
- Concept: Ensure that an event handler is called only once in a certain period of time when an event is continuously raised.
- Implementation method: using time stamp and timer to achieve, a total of three ways to achieve
Const throttleTimer = (func, delay) => {let timer = null Const throttleHandle = function () {const context = this const args = arguments; if (! timer) { timer = setTimeout(() => { func.apply(context, args) timer = null }, delay) } } return throttleHandle }Copy the code
// Timestamp const throttle = (func, delay) => {let startTime = date.now (); Return function () {const curTime = date.now (); const curTime = date.now (); Const remaining = delay - (curtime-startTime); const remaining = delay - (curtime-startTime); const context = this; const args = arguments; if (remaining <= 0) { func.apply(context, args); startTime = Date.now(); }}}Copy the code
// timer + timestamp const throttleTimeStap = (func, delay) => {let timer = null; let startTime = Date.now(); Return function () {const curTime = date.now (); const curTime = date.now (); Const remaining = delay - (curtime-startTime); const remaining = delay - (curtime-startTime); const context = this; const args = arguments; clearTimeout(timer); if (remaining <= 0) { func.apply(context, args); startTime = Date.now(); } else { timer = setTimeout(() => { func.apply(context, args); }, remaining); }}}Copy the code
The test demo shows how many times the event handler is fired when the window scrolls with and without throttling.
Not using throttling
Use the throttle
As you can see, with throttling, the number of times the event handler function Handle fires is significantly reduced, and the performance improvement is noticeable when the page is more complex.
Either a timestamp or a timer can be used in throttling. The timestamp + timer processing method uses startTime, curTime and delay to calculate remaining time in the function. Remaining <=0 indicates that the remaining event handler is executed, which ensures that the event handler can be executed immediately after the first triggering event and every delay time. If the remaining time is not reached, the remaining time is set to the remaining time. This ensures that the remaining event handler can be executed after the last event. Of course, if remaining fires another event, the timer will be cancelled and a remaining will be recalculated to determine the current state. To be more precise, the timestamp + timer is the best choice.
The difference between
Function throttling ensures that a true event handler is executed within a specified period of time, no matter how frequently the event is triggered, whereas function stabilization fires only once after the last event. For example, when verifying the mobile phone number entered by the user, it is more suitable to implement anti-shake. As long as the user keeps triggering the input, the real-time verification is not very good. When the user stops inputting, the verification rule will be triggered. For example, in the scenario of infinite page loading, we need the user to make Ajax requests every once in a while while the page is scrolling, rather than asking for data when the user stops scrolling. This scenario is suitable for throttling technology to achieve.