Anti-shake function and throttling function

Anti-shake function

As the name suggests, it prevents you from accidentally clicking twice with trembling hands, or it keeps shaking

The first type, such as fuzzy search, people have been typing, we want him to perform the search when he finishes typing, but we don't know when he ends, so we pretend that he hasn't typed for a certain period of time, just as he typed Finish

function generateDebounce(fn, delay) {
    let timer
    let args
    return function() {
        args = arguments
        window.clearTimeout(timer)
        timer = window.setTimeout(() => {
            fn(...args)
        }, delay)
    }
}

The second type of anti-shake, click the login button, and then accidentally click it multiple times, this is relatively simple

let loading = false
async function onClickLogin() {
    if (loading) return
    loading = true
    const result = await login(/** ...someArgs */)
    loading = false
}

Throttle function

As the name suggests, save traffic, this is very similar to anti-shake, the difference is that it is intentional, we hope that the continuous execution method will be executed in an interval, such as our scroll bar event, we have engaged in lazy loading of images, we need real-time comparison The position of the scroll bar, but there is no need to perform each comparison, we only need to make the user look continuous

function generateThrottled(delay, callback) {
  let timer
  let args
  return function throttled() {
    args = arguments
    if (timer) return
    timer = window.setTimeout(() => {
      callback(...args)
      timer = null
    }, delay)
  }
}

Guess you like

Origin blog.csdn.net/weixin_42335036/article/details/124332928