ByteDian: Can you cut it with your hands to reduce throttling and prevent shake?



Foreword

Recently, a blogger encountered such an interview question in Byte Interview. This question is also a high-frequency question in front-end interviews. Throttling and anti-shake are a very important means of front-end performance optimization, so as a front-end Engineers must master this knowledge point in depth. The blogger will explain it in detail here.

About the author: Programmer Xiaohao, a full-stack engineer, loves programming. He has worked for Nio and Tencent and now works for a major Internet company. Technology stack: Vue, React, Python, Java
This article is included in Xiaohao’s front-end series column. Some related articles on Getting started with front-end and front-end interviews will be updated in the future. It will take you step by step from learning front-end from scratch to interviewing and finding a job, and if you want to enter For students working in the front-end field, this front-end column will be helpful to you. You are welcome to follow it.
I will also continue to pay attention to some trends in AIGC and the field of artificial intelligence and summarize them in my blog. If you are interested, you can follow my artificial intelligence column.
Cloud native introductory learning series, if you are interested, you can take a look

Directory

  • Concepts and examples
      • Function debounce (debounce)
      • Function throttling (throttle)
  • summary
      • Combined with application scenarios
  • Conclusion

Concepts and examples

Function debounce

The callback will be executed n seconds after the event is triggered. If it is triggered again within these n seconds, the time will be reset.

Look at one (chestnut):

//Simulate an ajax request
function ajax(content) {<!-- -->
  console.log('ajax request ' + content)
}

let inputa = document.getElementById('unDebounce')

inputa.addEventListener('keyup', function (e) {<!-- -->
    ajax(e.target.value)
})

Take a look at the running results:



As you can see, as long as we press the keyboard, this ajax request will be triggered. Not only is it a waste of resources, but in actual applications, users only make requests after outputting complete characters. Let’s optimize it below:

//Simulate an ajax request
function ajax(content) {<!-- -->
  console.log('ajax request ' + content)
}

function debounce(fun, delay) {<!-- -->
    return function (args) {<!-- -->
        let that = this
        let _args = args
        clearTimeout(fun.id)
        fun.id = setTimeout(function () {<!-- -->
            fun.call(that, _args)
        }, delay)
    }
}
    
let inputb = document.getElementById('debounce')

let debounceAjax = debounce(ajax, 500)

inputb.addEventListener('keyup', function (e) {<!-- -->
        debounceAjax(e.target.value)
    })

Take a look at the running results:



As you can see, after we add anti-shake, the request will not be sent when you input frequently. The function will only be executed when you do not input within the specified interval. If input is stopped but input again within the specified interval, the timing will be retriggered. Watch another one:

let biu = function () {<!-- -->
    console.log('biu biu biu',new Date().Format('HH:mm:ss'))
}

let boom = function () {<!-- -->
    console.log('boom boom boom',new Date().Format('HH:mm:ss'))
}


setInterval(debounce(biu,500),1000)
setInterval(debounce(boom,2000),1000)

Take a look at the running results:



This is a good explanation. If the function is executed within the time interval, the timing will be retriggered. biu will be executed every 1s after the first 1.5s execution, but boom will not be executed even once. Because its time interval is 2s and the execution time is 1s, the timing will be retriggered every time

My personal understanding is that function anti-shake means that the mage must read the bar when issuing skills. If the skill bar is not finished reading, pressing the skill again will re-read the bar.

Function throttling (throttle)

It is stipulated that the function can only be triggered once within a unit of time. If the function is triggered multiple times within this unit time, only one will take effect.

Watch one:

 function throttle(fun, delay) {<!-- -->
        let last, deferTimer
        return function (args) {<!-- -->
            let that = this
            let _args = arguments
            let now = + new Date()
            if (last & amp; & amp; now < last + delay) {<!-- -->
                clearTimeout(deferTimer)
                deferTimer = setTimeout(function () {<!-- -->
                    last=now
                    fun.apply(that, _args)
                }, delay)
            }else {<!-- -->
                last=now
                fun.apply(that,_args)
            }
        }
    }

    let throttleAjax = throttle(ajax, 1000)

    let inputc = document.getElementById('throttle')
    inputc.addEventListener('keyup', function(e) {<!-- -->
        throttleAjax(e.target.value)
    })

Take a look at the running results:



As you can see, when we continue to input, ajax will be executed every 1 second according to the time we set.

Combined with what biubiubiu just said:

 let biubiu = function () {<!-- -->
        console.log('biu biu biu', new Date().Format('HH:mm:ss'))
    }

    setInterval(throttle(biubiu,1000),10)



No matter how small the execution time interval we set is, it will always be executed only once within 1 second.

Personal understanding: Function throttling is the rate of fire in FPS games. Even if you keep pressing the mouse to shoot, bullets will only be fired within the specified rate of fire.

Summary

  • Function anti-shake and function throttling both prevent frequent triggering at a certain time, but the principles between the two brothers are different.
  • Function anti-shake is executed only once within a certain period of time, while function throttling is executed at intervals.

Combined with application scenarios

  • debounce
    • Search Search Lenovo, when the user continues to enter values, anti-shake is used to save request resources.
    • When the window triggers resize, constantly adjusting the browser window size will continuously trigger this event. Use anti-shake to make it only trigger once.
  • throttle
    • Triggered by continuous mouse clicks, mousedown (triggered only once per unit time)
    • Listen for scrolling events, such as whether to slide to the bottom to automatically load more, use throttle to judge

Conclusion

Hello fellow readers, Xiaohao has established a technical exchange group. If you are very interested, you can send me a private message to join my community.

There will be many activities in the community from time to time, such as sharing of learning materials, sharing of interviews with major manufacturers, technical discussions, entrepreneurial talks by industry leaders, etc.

I am currently officially working in a major Internet company and have work experience in many major companies. Joining the community will also provide you with resume revision guidance, mock interviews, hands-on practical project teaching, opportunities for job referrals at major companies, and interviews with major companies. Question analysis and sharing and other benefits.

The community has many directions, and related fields include Web full stack (front-end and back-end), artificial intelligence, AIGC, self-media monetization, sharing of cutting-edge scientific and technological articles, intensive reading of papers, etc.

No matter how new you are, you are welcome to join the community to discuss, chat, and share, and we will help you become the next technology tycoon! You are always welcome to communicate with me, communicate and grow together. Realization, progress, technology, materials, projects, everything you want will be found here

The Internet will only get bigger and bigger. The bigger the storm, the more expensive the fish will be! Welcome to join the community ~ A person can go very fast, but a group of people will go further!

Everything you think is a question, and everything you do is an answer! Let’s start! Welcome to communicate with me in the comment area or backstage. You are also welcome to scan the QR code below to join my communication community directly! (WeChat: adcoderhao)