Discussion js function anti – shake and throttling

preface

Business development, in the front of the usual, everyone will involve the click event, and some browsers scroll event, when a user frequent operation code performance is low, the burden of aggravating the browser, lead to poor user experience, if we want to reduce the clean operating frequency of these events, we will use the function of image stabilization and throttle, In fact, the essence of the two functions are to reduce the frequency, next we will step by step to achieve the function of anti-shaking and throttling

Function debounce

Explanation: to prevent “Parkinson”, in the mode of frequency trigger, we only recognize once, next we will judge the parameter type, timer setting and clearing, whether to trigger immediately, the incoming native event first look at the overall structure of the function

Let box = document.querySelector('.box') /** *@param func[function,required] : wait[number]: set trigger frequency, default 300ms Immediate [Boolean]: Sets whether boundary triggering is enabled, */ function debounce (func, wait, Immediate) {return function proxy () {} function fn() {console.log('OK')} But we eventually want to execute fn, so we need to do some logic in the proxy to make fn execute once.Copy the code
  • Determine the parameter type

Debounce (fn) debounce(fn,300) debounce(fn,true) debounce(fn,300,true)

  • Timer setting and clearing

Set the timer in proxy and let fn execute it once

  • Whether triggered immediately

Func is triggered on the first click

  • Incoming event object

When box.onclick = function (ev) {} ev is passed in by the browser by default

Attach the complete code

function debounce (func, wait, immediate) { if (typeof func ! If (typeof wait === 'Boolean ') {immediate =. If (typeof wait ===' Boolean ') {immediate = true wait = 300 } if (typeof immediate ! == 'boolean') immediate = false if (typeof wait ! Wait = 300 var timer = null result = null return function proxy () {var nowRun =! Var self = this if(timer) var self = this if(timer) clearTimeout(timer) timer = setTimeout(() => { if (timer) { clearTimeout(timer) timer = null } ! immediate ? Result = func().apply(self.params) : null}, wait); nowRun ? Result = func().apply(self.params) : null V return resultV}}Copy the code

The function debounce has been written, and it will be more convenient to use it if it is developed using Vue. (Later, we will sort out the common custom instructions used in Vue development), so we will not repeat it here, and then we will throttle the function.

Function throttle

Reduce the trigger frequency, it can identify multiple times, such as browser scroll event trigger frequency is too high, we can use the throttle function to reduce the frequency Google 5-7ms, IE: 10-17ms, so that under the crazy operation, the frequency of Google Browser is 5ms once, throttling is to reduce this frequency, for example, we reduce to 300ms, under the crazy trigger, we indirectly control the interval of 300ms to execute once) the general structure of throttling is similar to the anti-shake, Except that our pass-through no longer determines whether to execute immediately, we demonstrate throttling by scrolling events

  • The basic structure
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="wlabelth=device-wlabelth, Word-wrap: break-word! Important; "> < span style> * {margin: 0; padding: 0; } html, body { height: 500%; background:-webkit-linear-gradient(top left, black, pink, blue); } </style> </head> <body> <script> /** *@param func[function,required] : wait[number]: set trigger frequency, default 300ms @return */ function throttle (func, wait) {return function proxy () {// core code}} function proxy () {console.log('OK'); } window.onscroll = debounce(fn,500) </script> </body> </html>Copy the code

After page scrolling, FN has a high execution frequency (as shown below) and low performance. Next, we optimize through throttling function

The throttling function is implemented in three aspects: parameter verification, timestamp mode and passing in the native event object. The reason why it is no longer judged whether to execute immediately is that throttling itself can be triggered many times, so it is no longer considered

  • Parameter calibration

  • Timestamp mode

  • Pass in the native event object

Throttling effect display

Attach the complete code

function debounce (func, wait) { if (typeof func ! == 'function') throw new TypeError("fun must be a function") if (typeof wait ! == 'number') wait = 300 var timer = null previous = 0 result = null return function proxy () Now = +new Date() self = this params = [].slice.call(arguments) Remaining = wait -(now-previous) // How many ms remains from the time of the incoming wait If (Remaining <= 0){// If remaining <= 0, the remaining time has expired. If (timer) {clearTimeout(timer) timer = null} result = func.apply(self,params) previous = +new Date() // The last click should be updated after each function execution}else if(! Timer) {// If the value is greater than 0 and the timer has not been set before, then we set the timer. Timer = setTimeout(function() {if(timer) {clearTimeout(timer) timer = null} result = remaining Func. Apply (self,params) previous = +new Date()},remaining)} return result}}Copy the code

To sum up, this is my summary of throttling and shaking prevention. My ability is limited. If there is any mistake, please kindly advise me.

Husband learning must be static also, only to learn also, not learn beyond wide only, not beyond into learning. Slow sex can not stimulate the essence, risk impetuous can not cure sex. Year and time chi, meaning and day go, then withered