JavaScript anti-shake and throttling!

Anti-shake and throttling

Original link: https://note.noxussj.top/?source=sifo icon-default.png?t=N2N8https://link.segmentfault.com/?enc=hYpLkGvY4Iz0kZPOBFQVJw%3D%3D.KBG3EkJ0qDJRL0yqVstbhtYttORnF%2F7O7aRKzdFxmlv25uFic8zyMcVc%2F77vf His

What is anti-shake?

It means that after an event is triggered multiple times at the same time, it will only be executed once. After multiple triggers, the time will be recalculated, and only the last trigger will take effect.

 

base case

Can be achieved through timer

 var timer = 0

    function click() {
        clearTimeout(timer)
 
        timer = setTimeout(function () {
            console.log('鼠标单击触发')
        }, 1000)
    }

    document.addEventListener('click', click)

Application scenarios

Submit button: All buttons that need to call interfaces after submission can add anti-shake to avoid calling repeated interfaces multiple times.

Browser window scaling: At certain times, it is necessary to monitor changes in the browser window and re-render the page after changes. Use anti-shake to prevent repeated rendering.


What is throttling?

This event will only be triggered for the first time within the specified time. Subsequent triggered events will be ignored until the timer expires.

base case

This can be achieved through timers and lock flags.

  var isLock = false

    function click() {
        if (isLock) return

        isLock = true

        setTimeout(function () {
            console.log('鼠标单击触发')
            isLock = false
        }, 1000)
    }

    document.addEventListener('click', click)

Application scenarios

Search box linkage query: The user enters the content value in the search box, and the displayed content can be returned by the scheduled query interface.

Verification code acquisition function: After obtaining the mobile phone verification code, it cannot be obtained again within the specified time.

Guess you like

Origin blog.csdn.net/start1018/article/details/129838011