[Summary]: JavaScript Interview Required Optimization Questions - Anti-shake Throttling - Application Scenario


1. Anti-shake

After the high-frequency event is triggered, it will only be executed once within n seconds, and the time will be recalculated if it is triggered again within n seconds.

Anti-shake design ideas:

  1. trigger event
  2. clear timing
  3. set timing

If there is still a request/event operation within the specified time, the timing will be cleared and the timing will be reset.
If there is no request/event within the specified time, submit or the following operations can be performed

Code

let btn = document.querySelector('button')

function payMoney() {
    
    
    console.log('已剁');
}

function debounce(payMoney, delay) {
    
    
    let timer  //1. 防止多次创建timer 2.(第二次点击时,由于闭包的原因 第一次的timer会存在)
    return function () {
    
    
        let context = this //保存button的this
        let args = arguments //参数
        clearTimeout(timer)
        timer = setTimeout(() => {
    
    
            payMoney.apply(context, args) //调用函数,修改this指向为context(button),添加参数
        }, delay);
    }
}

btn.addEventListener('click',debounce(payMoney,2000))

2. Throttling

High frequency events fire but only execute once in n seconds, so throttling dilutes how often the function executes.

Design ideas for throttling:

  1. trigger event
  2. Judgment: Is the trigger event within the time interval? Yes: do not trigger; no: trigger
  3. set timing

If there is still a request/event operation within the specified time, this request/event operation will be required to wait for the first event trigger.

Code

function coloring() {
    
    
	let r = Math.floor(Math.random() * 255)
	let g = Math.floor(Math.random() * 255)
	let b = Math.floor(Math.random() * 255)
	document.body.style.background = `rgb(${
      
      r},${
      
      g},${
      
      b})`
}

function throttle(coloring,delay) {
    
    
    let timer
    return function() {
    
    
        let contxt = this
        let args = arguments

        //判断:如果有timer,说明上一个时间还未结束
        if(timer) {
    
    
            return  //没结束你就return停止,等上一个结束
        }
        timer = setTimeout(() => {
    
    
            coloring.apply(contxt,args)
            timer = null  //timer不在事件完成之后给null的话,上面的if会一直判断为真
        }, delay);
    }
}

window.addEventListener('resize',throttle(coloring,2000))

3. Summary

防抖: Combine multiple operations into one operation. The principle is to maintain a timer, which stipulates that the function is triggered after the delay time, but if it is triggered again within the delay time, the previous timer will be cancelled and reset. This way, only the last action can be triggered.

节流: Makes the function trigger only once within a certain period of time. The principle is to judge whether there is a delayed call function that is not executed.

the difference

Function throttling ensures that no matter how frequently the event is triggered, the real event handler will be executed once within the specified time, while function anti-shake only triggers the function once after the last event.
For example, in the infinite loading scenario of the page, we need the user to send an Ajax request every once in a while while scrolling the page, instead of requesting data when the user stops scrolling the page. Such a scenario is suitable for throttling technology to achieve.

Guess you like

Origin blog.csdn.net/weixin_60297362/article/details/123315692