SoFunction
Updated on 2025-04-04

Methods of using anti-shake and throttling in Vue

What is anti-shake/throttling

First, let’s talk about what anti-shake and throttling are

Anti-shake(debounce)

Anti-shake means that the same event will be triggered multiple times over a period of time, but our purpose is just to let them execute the event after it is not triggered, such as mousemove, input box change, etc. At this time, we need a method to control it. After the event is not executed for a period of time, the event is executed, which is anti-shake.

Throttle(throttle)

Throttle means that the same event will be triggered multiple times in a short period of time, but our purpose is to make them only trigger once in a given time, such as scroll event (scroll), mouse click event (click), etc. At this time, we need a method to control it. Events can only be triggered once within a period of time (0.5S/1S), that is, throttling.

Anti-shake (debounce)

// Anti-shakeexport default function debounce(fn, time) {
  time = time || 200
  // Timer  let timer = null
  return function(...args) {
    var _this = this
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function() {
      timer = null
      (_this, args)
    }, time)
  }
}

Throttle

// throttlingexport default function throttle(fn, time) {
  let timer = null
  time = time || 1000
  return function(...args) {
    if (timer) {
      return
    }
    const _this = this
    timer = setTimeout(() => {
      timer = null
    }, time)
    (_this, args)
  }
}

Page usage

Just use click speed to simulate the frequency of triggering events

<el-button @click="clickDebounce">Anti-shake</el-button>
<el-button @click="clickThrottle">Throttle</el-button>
//Reference the defined JS methodimport debounce from '@/utils/debounce'
import throttle from '@/utils/throttle'
methods: {
    clickDebounce: debounce((e) => {
      (1)
    }, 1000),
    clickThrottle: throttle((e) => {
      (2)
    }, 1000),
}

Use scenarios

There are many usage scenarios according to business needs. Let me give you two simple examples.

Anti-shake (debounce)When the search box is automatically searched, the search drop-down box can be searched remotely. If the user has not finished entering, anti-shake can save the requested resources.
When the mouse moves, the mouse stops and then executes the method

ThrottleWhen scrolling the page

Summarize

That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!