preface


Knowledge only with practice, absorb internalized into their own things, in order to use the time lifting weight as light, freely.

Questions themselves


  1. What are the usage scenarios for tremble and throttling? What’s the purpose of using these two things?
  2. What do you mean by shockproof and throttling? Why is it called that? What’s the difference?

Usage scenarios


The birth of technology is to solve the problems encountered in real life, the birth of the Internet to solve the space distance caused by the obstacles to communication. To understand the background of the birth of a certain knowledge, then more able to understand the connotation of this knowledge point.

In front end development, we often come across scenarios where browser events are triggered very frequently.

  1. Scenario 1: In mobile web pages, there is often a back to top button in the bottom right corner, and this button usually appears after scrolling down a certain distance. So how do you know how far down the page has been? The scroll event of the page that needs to be monitored. The code is as follows,
window.addEventListener('scroll', () =>{ const scrollTop = document.body,scrollTop || document.documentElement.scrollTop; Console. log(' page scroll distance ', scrollTop); }, false)Copy the code

After actually running the above code, one problem is that scroll events are fired too often. A small scroll with the mouse wheel triggers the event 4 or 5 times. This doesn’t do much good to our business logic, and it hurts browser performance.

Validation of input characters is a common requirement, and can be time-consuming if your validation logic requires a call to the back-end interface. For example, search box input, each input, to call the API query associated with the term drop-down display. In this case, we don’t want to drop the interface every time we input it (because sometimes it’s pinyin), but instead call the interface after the input is complete.

To summarize, the application scenarios mentioned above. Events are triggered too often, which hurts browser performance. As a developer, you want to be able to control the comments triggered by events in a way that doesn’t affect the business logic. This is the purpose of damping and throttling — controlling how often events are triggered.

Image stabilization (debounce)


Having said that we wanted to find a way to control the frequency at which events were triggered, different developers had different ideas to solve the problem, and two of the ideas that have been tested and accepted are shockproofing and throttling.

Based on the above scenario, the first idea is proposed: when the event is triggered for the first time, the function is not executed immediately, but a deadline value such as 200ms is given, and then:

  • If the event is triggered again within 200ms, the current timing is cancelled and the timing starts again
  • If the event is not fired within 200ms, the event handler is executed

Effect: Events are fired continuously for a specified period of time, and the handler is executed only once after the specified time after the last event was fired.

Code implementation:

Function debounce(fn, delay) {let timer; return function() { if (timer) clearTimeout(timer); timer = setTimeout(fn, delay); } } window.addEventListener('scroll', debounce(() => { let scrollTop = document.body.scrollTop || document.documentElement.scrollTop; Console. log(' page scroll distance ', scrollTop); },1000), false);Copy the code

In practice, you can see that the handler is executed only after the scrolling has stopped for one second.

The throttle (throttle)


Moving on from this, if you use the stabilization solution, a new problem arises: if a user is idle and scrolling, then in theory the scrolling event handler will not be executed. Because the processing function is executed only after the scrolling has stopped for a second. The result is unwanted by the product, which wants to be able to execute the handler once in a while, even if the user is constantly scrolling through the page. Similar skill cooldown, cannot be used during the cooldown.

So we can give the idea: when the event is first fired, it does not execute the function immediately. Instead, it gives a time limit such as 200ms, starts the timer, and then

  • Within 200ms, all events that are fired again are ignored. After the timer is finished, the function is executed once and the timer is cleaned up.
  • At the end of 200ms, start the above cycle again

Effect: If a large number of the same events are fired in a short period of time, after a function is executed once, the function ceases to work for a specified period of time until it retakes effect after that time.

Code implementation:

function throttle(fn, delay) { let timer; return function() { if (! timer) { timer = setTimeout(() => { fn(); clearTimeout(timer); timer = null; }, delay) } } } window.addEventListener('scroll', throttle(() => { let scrollTop = document.body.scrollTop || document.documentElement.scrollTop; Console. log(' page scroll distance ', scrollTop); },1000), false);Copy the code

Conclusion:


Buffering and throttling are two ways to solve the problem of too many events being fired for a short time. Buffering is dynamic, and the handler is executed only after the last event has been fired. There is no function processing in the middle, preventing the page “jitter”, can be considered to ensure the process of continuous smoothness. Throttles are discrete and explicitly split in time, executing the event handler only once in a specified time block.