preface

Personal throttling wood what feeling, so want to throttling function for a review, to sum up.

The body of the

Let’s start with what is throttling? Why cut back? What does it do? How to write?

What is throttling?

After the event is triggered, no matter how it is triggered within the specified time, the function will only be called once until the end of time. Personal understanding is that the game character's bully, how we hit him during the bully, he will not fall, can only wait for the end of time bully effect disappearCopy the code

Why anti-shake? What does it do?

Optimize project performance to make the project run faster and better. Reducing the amount of time spent on frequent calls such as Scroll or mousemove is also important because interviews may ask questions that we need to know.Copy the code

How to write?

The timer version

The first parameter is the function we're going to execute and the second parameter is the timefunction throttle(func,delay){
  let timer = null
  retrun function(. args){
    // let args=arguments can also be written as this or... Args is also an argument that we pass in
    if(! timer){ timer=setTimeOut(() = >{
         func.apply(this,args)
         timer=null
      },dealy)    
    }
    // When we first fire the event, we execute the function when the timer does not exist. When we click again, because the timer exists,
    // So there is no way to enter the function call (no matter how the event is executed), so you have to wait for the timer event to end,
    // we set timer=null, return to the first state, and start the new round again}} this kind of functional function, actually will use a lot of places, we can wrap it into a JS file, throughexport functionExport it, import it into a concrete use file and call the functionCopy the code

The time stamp version

function throttle(func,delay){
   let start=0
   //let start=+new Date(
   return function(. args){
     let now=+new Date(a)// The + sign can be converted to a timestamp
     if(now-start>delay){
       func.apply(this,args)
       start=now
     }
   }
   // The event will be triggered immediately for the first time, and the function will be called to check whether the interval between the events triggered is longer than the set waiting time
   // If the value is greater than the specified time, the function can be called again, otherwise vice versa
}
Copy the code

Time stamp version and timer version difference

The difference between the two is that the timestamp version is executed immediately and seems to exist for a reason, while the timer version is executed immediately for the last time.

But the timer version can also be executed immediately for the first time. In fact, with a little modification can be achieved.

function throttle(func, delay) {
    let timer = null
    return function (. args) {
      if(! timer) { func.apply(this, args)// Execute the function first
        timer = setTimeout(() = > {
          timer = null;
        }, delay)
      }
    }
  }
Copy the code

How to use?

Here is a combination of small cases, the following is the timer version

The throttling function is not used

<div id="box"></div>
let box = document.getElementById('box')
let count = 1;
function doSomething() {
  box.innerHTML = count++;
  console.log('1')}; Box. Onmousemove = doSomething When we talk about moving the mouse around in a box, it's going to increase like crazy, it's going to print all the time1
Copy the code

rendering

The throttling function is used

let box = document.getElementById('box')
let count = 1;
function doSomething() {
    box.innerHTML = count++;
    console.log('1')};// box.onmousemove = doSomething
box.onmousemove = throttle(doSomething, 2000);
Copy the code

The result is as follows, the number of times to print is reduced, it is recommended to experience on the computer (write blog outside, no tools, otherwise it will be changed to GIF).

additional

I heard that if the interviewer is BT, you will be asked to write the first time also perform, or in the middle of the throttling, the last time also to perform. This time can not say not, but we invincible B highlight moment arrived, the timer and timestamp merge, commonly known as the throttling body double revision. Hey hey hey hey!

Throttle body double revision

function throttle(func, delay) {
  let start=0
  let timer=null
  return function (. args) {
    let now = +new Date(a);if (now - start < delay) {
       if (timer) clearTimeout(timer)
       // timer && clearTimeout(timer
       // if the left side is false then the right side is not computed.
        timer = setTimeout(() = > {
            start = now;
            func.apply(this, args);
        }, delay);
       } else {
         start = now;
         func.apply(this, args); }}}Copy the code

conclusion

The throttling function is to reduce the firing frequency of events within a certain time range

The difference between the timestamp version and the timer version is that the timestamp version is executed immediately, while the timer version is executed immediately for the last time, but the timer can also be executed for the first time

Combined with Application Scenarios

1. Search box association: when users input values, they personally think that function throttling can also reduce the number of requests for data, but it is more used for shaking prevention.

2. In the page loading scenario, users can send Ajax requests at regular intervals while scrolling the page

4. 3. Smart laundry peg

If you’re interested you can check out my Debounce

Debounce && The role of the anti – shock function

expand

SegmentFault: Function throttling and function stabilization

Nuggets: function throttling and function anti – shake

Alloween: prevent and throttle