High-frequency interview handwritten code practice 1--anti-shake throttling

Anti-shake:

If the same event is triggered a large number of times in a short period of time, the function will only be executed once. --scroll

The page resize event is common when page adaptation is required. Dom rendering needs to be performed according to the final rendering of the page (in this case, anti-shake is generally used, because only the last change needs to be judged)

function debounce(fn,delay){
    let timer=null
    let that=this
    return function(){
      if(timer){
        clearTimeout(timer)
      }
      timer=setTimeout(()=>{
        fn.call(that,...arguments)
      },delay)
    }
   
}

Throttling:

If a large number of the same event is triggered in a short period of time, after the function is executed once, the function will no longer work within the specified time period, and will not be effective again until this period of time has elapsed.

 The input event of the search box, for example, to support input real-time search, you can use the throttling scheme (relevant content must be queried after a period of time), or to realize that the input interval is greater than a certain value (such as 500ms), it will be regarded as the completion of the user input, and then start the search. Which solution to use depends on business needs.

function throttle(fn,delay){
    let flag=true
    let that=this
    return function(){
        if(!flag){return false}
        flag=false
        setTimeout(()=>{
            flag=true
            fn.call(that,...arguments)
        },delay)
    }
}

 

Guess you like

Origin blog.csdn.net/qq_33168578/article/details/114089896