Commonly used front-end algorithms (1): anti-shake + throttling

Table of contents

Chapter 1 Anti-Shake

1.1 Introduction to debounce

1.2 Application scenarios

1.3 Implementation ideas

1.4 Hand tearing anti-shake code

Chapter 2 flow

2.1 Introduction to throttling

2.2 Application scenarios

2.3 Implementation ideas

2.4 Manual throttling code (method: timestamp and timer)

2.5 The difference between timestamp and timer implementation

Summary of Chapter 3


Chapter 1 Anti-Shake

1.1 Introduction to debounce

  • Scenario: The user frequently clicks to execute a function/event for a period of time. During this period, the user clicks once and the timer is re-timed . When the user does not trigger the function/event during this period, the function/event will Executed at the end of this period.
  • Application example understanding: The return to the city is interrupted , and the player has residual blood to prepare to return to the city. It takes 3 seconds for the return to the city to be successful, but during this 3s process, the player clicks the return to the city again, causing the 3s return to the city to be recalculated and wait for another 3 seconds.

1.2 Application scenarios

  • Buttons/events such as logging in, sending text messages , and sending post requests prevent users from clicking too fast and sending multiple requests. Anti-shaking is required and the last request can be sent;
  • When resizing the browser window , the resize times are too frequent, resulting in too many calculations. At this time, it needs to be done in one go, so anti-shake is used;
  • The input input box obtains the value once without entering a character. You can use anti-shake to obtain the value after the input is completed.
  • The text editor saves in real time and saves after one second without any changes.
  • ……

1.3 Implementation ideas

 

1.4 Hand tearing anti-shake code

function debounce(func,delay) {
    // 定义一个定时器timer
    let timer = null
    return function() {
        const that = this
        const args = arguments
        // 防抖核心:每次触发事件计时器都会重新计时
        clearTimeout(timer)
        timer = setTimeout(()=>{
            func.apply(that,args)
        },delay)
    }
}
  • example:

When the anti-shake function is not called: every time the user enters/delete a value in the input, a value will be output;

    <input type="text" id="input">

    <script>
        let inputDom = document.getElementById('input')
        //获取输入框的输入内容
        inputDom.oninput = function(){
          console.log('this.value',this.value)
        }
    </script>

 

 

After calling the anti-shake function: a value will be output after the user inputs/deletes a value delay.

    let inputDom = document.getElementById('input')
    //func 是执行函数,delay 是事件执行的延迟时间,毫秒
    function debounce(func,delay) {
        // 定义一个定时器timer
        let timer = null
        return function() {
            const that = this
            const args = arguments
            // 防抖核心:每次触发事件计时器都会重新计时
            clearTimeout(timer)
            timer = setTimeout(()=>{
               func.apply(that,args)
            },delay)
        }
    }
    function handler() {
        console.log('this.value',this.value)
    }
    inputDom.addEventListener('input', debounce(handler, 1000))

Chapter 2 flow

2.1 Introduction to throttling

  • Scenario : The user frequently clicks to execute a function/event for a period of time. During this period, the user clicks once/multiple times (calling the event) without affecting the timer execution, and the function/event is only executed once.
  • Application example understanding: During the skill cooldown , the player used the flash skill under certain circumstances, but the cooldown time of this skill is 120s. During this period, the player encountered danger and wanted to use the flash skill again. Frequently Clicking it, but it's useless, the flash will not be executed, the timer is still counting down, and you can't use the flash skill again until the 120s countdown reaches 0.

2.2  Application scenarios

  • window adjustment
  • Page scrolling
  • Panic buying and crazy clicking
  • Lazy loading to get the position of the scroll bar
  • The mouse continuously triggers an event (such as a click) and only triggers it once within a specified time.
  • ……

2.3  Implementation ideas

2.4 Manual throttling code (method: timestamp and timer)

// ---------------------节流1:使用时间戳---------------------
//func 是事件处理程序,delay 是事件执行的延迟时间,单位:毫秒
function throttle (func, delay) {
    //定义初始时间(开始触发事件的时间)
    let start = 0;
    return function () {
        const that = this
        const args = arguments
        // 获取当前时间戳
        let cur =Date.now()
        // 时间间隔大于延迟时间则进入
        if (cur - start >= delay) {
            //执行事件处理程序
            func.apply(that, args);
            //更新初始时间
            start = cur
        }
    }
}
// ---------------------节流2:使用定时器---------------------
//func 是事件处理程序,delay 是事件执行的延迟时间,单位:毫秒
function throttle(func, delay){
    // 自定义一个定时器
    var timer = null;
    return function(){
        var that = this;
        var args = arguments
        // timer为null表示可以发送请求了,否则还在请求中,不执行事件
        if(!timer){
            timer = setTimeout(function(){
                //执行事件处理程序
                func.call(that, args)
                //事件执行完后把定时器清除掉,下次触发事件的时候再设置
                timer = null;
            }, delay)
        }  
    }
}
  •  example:

When the throttling function is not called, each time the button is clicked, a function call will be executed:

<button id="button1">发送了节流请求</button>
const button1Dom = document.getElementById('button1')
button1Dom.addEventListener('click',function(){
    console.log("节流:我发送了消息")
})

 After using the throttling function, if you click to send a request frequently, it will be sent again after the timer expires. After clicking to send a request during this period, no more requests will be sent:

const button1Dom = document.getElementById('button1')
// ---------------------节流1:使用时间戳---------------------
//func 是事件处理程序,delay 是事件执行的延迟时间,单位:毫秒
function throttle (func, delay) {
    //定义初始时间(开始触发事件的时间)
    let start = 0;
    return function () {
        const that = this
        const args = arguments
        // 获取当前时间戳
        let cur =Date.now()
        // 时间间隔大于延迟时间则进入
        if (cur - start >= delay) {
            //执行事件处理程序
            func.apply(that, args);
            //更新初始时间
            start = cur
        }
    }
}
// ---------------------节流2:使用定时器---------------------
//func 是事件处理程序,delay 是事件执行的延迟时间,单位:毫秒
// function throttle(func, delay){
//     // 自定义一个定时器
//     var timer = null;
//     return function(){
//         var that = this;
//         var args = arguments
//         // timer为null表示可以发送请求了,否则还在请求中,不执行事件
//         if(!timer){
//             timer = setTimeout(function(){
//                 //执行事件处理程序
//                 func.call(that, args)
//                 //事件执行完后把定时器清除掉,下次触发事件的时候再设置
//                 timer = null;
//             }, delay)
//         }  
//     }
// }
button1Dom.addEventListener('click',throttle(function(){
    console.log("节流:我发送了消息")
},1000))

Frequent clicks reduce the frequency of sending: 

 

2.5 The difference between timestamp and timer implementation

The most obvious difference is that when you click frequently, you will find that throttling using timestamps will be executed immediately when called , while using timers will be executed at the end of the time period.

Summary of Chapter 3

  • The so-called anti-shake means that after the event is triggered, the function will not be executed until n seconds. If the event is triggered again within n seconds, the function execution time will be recalculated; throttling means that the event is triggered continuously, but within n seconds The function is only executed once.
  • Function throttling will ensure that the real event processing function will be executed once within the specified time no matter how frequently the event is triggered, while function anti-shake only triggers the function once after the last event.

Guess you like

Origin blog.csdn.net/qq_45796592/article/details/132315247