vue3节流防抖

<template>
  <div>
    <a-button @click="throttle" type="primary">节流</a-button>
    <a-button @click="debounce" type="primary">防抖</a-button>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
//防抖,在一段时间内会执行一次,如果在这个时间段内再次触发,重新计算时间(用作提交事件,防止重复提交)
function debounce (fn:any, delay:number) {
  let timer:any
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn()
    }, delay)
  }
}
//节流,在一段时间内,函数最多可以触发一次执行
function throttle (fn:any, delay:number) {
  let isThtottle = ref(true)
  return () => {
    if (!isThtottle.value) return
    isThtottle.value = false
    setTimeout(() => {
      fn()
      isThtottle.value = true
    }, delay)
  }
}
// 节流
const throttle=throttle(()=>{
  console.log('节流触发')
},2000)
// 防抖
const debounce=debounce(()=>{
  console.log('防抖触发')
},2000)
</script>

<style scoped lang="less">

</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值