vue3+ts 防抖与节流的简单示例
<script setup lang="ts">
import {ref} from 'vue'
const debounceCount = ref(0)
const throttleCount = ref(0)
//防抖
const debounce = (fn, delay: number) => {
let timer = null
return function () {
// 保留调用时的this上下文
let context = this
// 保留调用时传入的参数
let args: any = arguments
// 每次事件被触发时,都去清除之前的旧定时器
clearTimeout(timer)
// 设立新定时器
timer = setTimeout(() => {
fn.apply(context, args)
}, delay);
}
}
// 节流
const throttle = (fn, delay) => {
let timer = null;
return function () {
// 保留调用时的this上下文
let context = this
// 保留调用时传入的参数
let args: any = arguments
if (timer) {
return
}
timer = setTimeout(() => {
fn.apply(context, args)
timer = null
}, delay)
}
}
const clickBtn: (num: number) => void = debounce(
(num) => {
debounceCount.value = num + 1
},
1000
)
const clickThrottleBtn: (num: number) => void = throttle(
(num) => {
throttleCount.value = num + 1
},
500
)
</script>
<template>
<div class="card">
<button type="button" @click="clickBtn(debounceCount)">debounceCount is {{ debounceCount }}</button>
<p/>
<button type="button" @click="clickThrottleBtn(throttleCount)">throttleCount is {{ throttleCount }}</button>
</div>
</template>