Skip to content

防抖


在单位时间内频繁触发事件,只有最后一次生效
应用场景:① 手机号、邮箱地址的校验,② 当用户input框输入完成后再发请求,如搜索等

基本使用

vue

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { debounce } from 'vue-hkp-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>

内部方法

vue
<script setup lang="ts">
function debounce (fn: Function, time = 300): any {
  let timer:any;
  return (...args) => {
    const context = this;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.call(context, ...args);
    }, time);
  };
}
</script>

Released under the MIT License.