In the common browser web PAGE B/S architecture, requests sent by the user on the web page are quickly sent to the server.

If the user sends too many requests, the back end may not be able to process them quickly, or some functions may be executed too many times, and the browser may freeze. So the anti – shake function and throttling function came into being.

The debounce function is essentially a custom function that handles the delay function through setTimeout() :

/* * fn [function] delay [number] delay, Return function() {if(timer){clearTimeout(timer) */ function debounce(fn,delay){let timer = null // Enter the branch statement, indicating that a timing process is currently underway and the same event is triggered again. Timer = setTimeout(fn,delay)}else{timer = setTimeout(fn,delay)}Copy the code

Use case: debounce(submit(), 200)

Effect: If the same event is fired many times in a short period of time, the function is executed only once.

Implementation: Since the timing was mentioned earlier, the key to the implementation is the setTimeout function. Since we also need a variable to hold the timing, consider maintaining global purity, which can be achieved with the help of closures.

Anti-shake functions have dealt with the problem of some functions being executed too many times, but they are not perfect. When the user triggers a large number of events in a short time, the function will be triggered only after the delay milliseconds after the user stops triggering. If the user has the following requirements: Some requests can be continuously sent when the request function is constantly executed, such as printing its position on the console when the browser scroll bar is sliding.

We know that the position of the browser scroll bar is continuous, and printing the position directly will cause the printing function to execute too many times, causing the browser to freeze. However, when the anti-shake function is adopted, the scrollbar position will be printed only once after the user releases the mouse stop delay milliseconds, which does not meet the requirement of users to print the scrollbar position dynamically in real time.

Throttle can satisfy the above requirements:

(There is more than one implementation, and this is just an example. The throttling function can even dispense with setTimeout altogether, replace the status bit with a timestamp, and determine if the timestamp difference is greater than the specified interval.)

function throttle(fn,delay){ let valid = true return function() { if(! Valid){// Rest time no call return false} // Work time, execute the function and set the status bit to invalid during the interval valid = false setTimeout(() => {fn() valid = true; }, delay) } }Copy the code

To implement the throttling function without using the timestamp of setTimeout:

function throttle(fn, delay) { var previous = 0; Previous return function() {var _this = this; var args = arguments; var now = new Date(); if(now - previous > delay) { fn.apply(_this, args); previous = now; } } } // test function testThrottle(e, content) { console.log(e, content); } var testThrottleFn = throttle(testThrottle, 1000); Onmousemove = function (e) {testThrottleFn(e, 'throttle'); // Pass the parameter to the throttling function}Copy the code

This is a function that opens periodically, like a control valve. When the function is run once, it is temporarily disabled for a certain period of time, after which it is reactivated.

Effect: If a large number of the same events are fired in a short period of time, the function stops working for a specified period of time after it executes once.

In the case of printing scroll bar positions above, apply the throttling function:

Document.onscroll = throttle(function() {console.log(‘scroll event triggered ‘+ date.now ())}, 200) document.onscroll = throttle(function() {console.log(‘scroll event triggered’ + date.now ())}, 200) The location of the scroll bar is printed on the console every 200 milliseconds, which is what the user wants.

Conclusion:

There are many applications of the anti-shake/throttling function at present. In addition to the above cases, specific examples include:

Buffering: Every resize/scroll trigger statistical events and text input verification (AJAX requests sent after continuous text input are verified only once)

Throttling: Google search box/search association, high-frequency click intermittent submission, repeated submission of forms;

And so on.

Even with a lot of framework tools on the front end, we can’t get around native JavaScript scripts when we’re dealing with some problems,

Therefore, to master a solid foundation of knowledge, in the face of problems actively mobilize logic.