What's the difference between anti-shake and throttling?

1. Understanding anti-shake and throttling

Anti-shake: Trigger events frequently within a unit of time, only the last time will take effect

For example: when the game is interrupted when returning to the city, the time will be restarted if you click on returning to the city again. In the end, only the last time that has not been interrupted can return to the city successfully, which is anti-shake

Throttling: Events are frequently triggered in unit time and only take effect once (that is, only take effect for the first time)

For example, if the mouse clicks on the next carousel image, no matter how many times the carousel is clicked in a unit time, the carousel image will be replaced in 2 seconds, which is throttling

Both anti-shake and throttling are a means of performance optimization

Two, the same

1. Both can be achieved by using setTimeout

2. Both can reduce the frequency of callback execution and save computing resources

3. Differences

1. Different definitions

Function anti-shake: trigger events continuously for a period of time, only execute the last time

Function throttling: Execute only once within an event

2. Different application scenarios

Anti-shake: (1) Verification of mobile phone number and email address (2) After the user enters the input box, send a request, such as search, etc.

Throttling: high-frequency events, such as: after how many seconds to get the verification code, resize event and scroll event, etc.

4. Code implementation

1. Anti-shake:

<body>

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

  <script>

    // 1. Anti-shake

    document.querySelector('#i').addEventListener('input', () => {

      debounce()

    })

    let timeId = null

    const debounce = () => {

      clearTimeout(timeId)

      timeId = setTimeout(() => {

        console.log("The last output of anti-shake");

      }, 1000)

    }

  </script>

</body>

 Anti-shake effect:

2. Throttling:

<body>

   <input type="button" id="btn" value="Get verification code">

  <script>

   

// 2. Throttling

    let flag = true // set the control switch

    let timeId = null

    const inp = document.querySelector('#btn')

    inp.addEventListener("click", () => {

      if (!flag) {

        return

      }

      flag = false

      let s = 5

      timeId = setInterval(() => {

        s -= 1

        if (s < 1) {

          inp.value = 'Get Verification Code'

          flag = true

          s = 5

          clearInterval(timeId)

        } else {

          inp.value = s + 'Get the verification code again in seconds'

        }

      }, 1000)

    })

  </script>

</body>

Guess you like

Origin blog.csdn.net/weixin_48082900/article/details/128901788