Introduction:

During the development process, have you encountered the following business operations:

Case 1: The submit button is clicked repeatedly and the user enters the box to search; Case two: monitor page scrolling, monitor mouse movement, etcCopy the code

If that happens, we need to do some optimization

Image stabilization (debounce)

Such as submit button to prevent repeated click, or user edit input box OnChange event data request operation; If you call the interface at this high frequency, the back end will probably come at you with a brick. Ha ha ha!!! If triggered repeatedly within the specified interval, the state will be cleared and only triggered after the specified interval is exceeded

As shown: custom methods are triggered only after clicking for a second, in this case 1 second;

The following code

 let btn = document.getElementById('btn')

  btn.addEventListener('click',debounce(clickFn))

  function debounce(fn){
    lettime = null; // Define the initial valuereturn function(... Args){clearTimeout(time) // Clear the state every time it is triggered time =setThe Timeout (() = > {fn. Apply (this, args) / / perform incoming function}, 1000)}}function clickFn(){
    console.log('Click on me.')}Copy the code

The throttle (throttle)

Such as monitoring mouse sliding events and monitoring page scrolling events; The idea is to fire only once at a specified interval

Above:

The code is as follows:

  window.addEventListener('scroll',throttle(scrollFn))

  function throttle(fn){
    let run = true; // Define the initial valuereturn function(... args){if(! Run){// State change returns directlyreturn
      }


      run = false// Change the statesetTimeout(()=>{ fn.apply(this,args); // Execute the passed function run =true// reinitialize data},1000)}}function scrollFn(){
    console.log('Watch me print it once a second.')}Copy the code

conclusion

Debounce and throttle also play a role in front-end optimization. This is the end of sharing, if it helps you, please don’t be stingy with your likes; Ha ha ha!!!!!!

Front end of a pupil!!