<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>
vue3节流防抖
最新推荐文章于 2025-04-26 15:16:40 发布