Skip to content
On this page

throttle 节流


高频触发同一事件,在函数执行一次之后,该函数每隔指定时间(delay)执行一次

Code
ts
function throttle(fn: Function, deplay = 300) {
  let timer: any = null
  return function (this: unknown, ...args: any[]) {
    const context = this
    if (!timer) {
      timer = setTimeout(() => {
        timer = null
        fn.apply(context, args)
      }, deplay)
    }
  }
}

基本使用

打开控制台查看输出

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

onMounted(() => {
  document.onscroll = throttle(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