Skip to content
On this page

debounce 防抖


对于短时间内连续触发的事件,在 delay 时间内函数只执行最后一次

Code
ts
function debounce(fn: Function, delay = 300) {
  // timer 是在闭包中的
  let timer: number | null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn()
      timer = null
    }, delay)
  }
}

基本使用

打开控制台查看输出

vue
<script setup lang="ts">
import { onMounted, onUnmounted } from "vue"
import { debounce } from "@jqw755/q-ui"

onMounted(() => {
  document.onscroll = debounce(showPosition, 1000)
})
onUnmounted(() => {
  // 移除键盘切换事件
  document.onscroll = null
})
function showPosition() {
  const scrollTop = document.body.scrollTop || document.documentElement.scrollTop
  console.log("滚动条位置:" + scrollTop)
}
</script>

APIs

参数说明类型默认值必传
fn要执行的函数Function-true
delay防抖时间期限,单位 msnumber300false

License