Home  >  Article  >  Web Front-end  >  JS anti-shake and throttling

JS anti-shake and throttling

Guanhui
Guanhuiforward
2020-05-02 12:29:422126browse

Concepts and examples

Function debounce(debounce)

Execute the callback n seconds after the event is triggered. If here If it is triggered again within n seconds, the time will be reset.

Look at one (chestnut):

//模拟一段ajax请求
function ajax(content) {
  console.log('ajax request ' + content)
}
let inputa = document.getElementById('unDebounce')
inputa.addEventListener('keyup', function (e) {
    ajax(e.target.value)
})

Copy the code and take a look at the running results:

JS anti-shake and throttling

You can see that we only need to 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:

//模拟一段ajax请求
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)
    })

Copy the code and take a look at the running results:

JS anti-shake and throttling

As you can see, after we add anti-shake, when you are frequently When inputting, no request will be sent, and the function will be executed only if you have no input within the specified interval. If input is stopped but input again within the specified interval, the timing will be retriggered.

Look at 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)

Copy the code and take a look at the running results:
JS anti-shake and throttling

This is a good explanation, if it is executed within the time interval function, 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 of function anti-shake is that the mage has to read the bar when sending skills. If the skill bar is not finished reading, press the skill again. Will re-read the article.

Function throttling (throttle)

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

Look at one:

function throttle(fun, delay) {
        let last, deferTimer
        return function (args) {
            let that = this
            let _args = arguments
            let now = +new Date()
            if (last && 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(&#39;throttle&#39;)
    inputc.addEventListener(&#39;keyup&#39;, function(e) {
        throttleAjax(e.target.value)
    })

Copy the code and look at the running results:

JS anti-shake and throttling

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

Combined with what biubiubiu just said:

    let biubiu = function () {
        console.log(&#39;biu biu biu&#39;, new Date().Format(&#39;HH:mm:ss&#39;))
    }
    setInterval(throttle(biubiu,1000),10)

JS anti-shake and throttling

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

Personal understanding: Function throttling is the rate of fire of 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 Lenovo, use anti-shake to save request resources when the user continuously inputs values.

When window triggers resize, constantly adjusting the size of the browser window will continuously trigger this event. Use anti-shake to make it only trigger once.

throttle

The mouse keeps on Click to trigger, mousedown (only triggered once per unit time)

Listen to scroll events, such as whether to slide to the bottom and automatically load more, use throttle to judge

The above is the detailed content of JS anti-shake and throttling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete