- 防抖是触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
- 节流是高频事件触发,但在n秒内只会执行一次,如果n秒内触发多次函数,只有一次生效
export function debounce(fn,delay=500){
let timer = null
return function(){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(this)
},delay)
}
}
export function throttle(fn, delay = 500) {
let timer = true;
return function () {
if (!timer) return;
timer = false;
setTimeout(() => {
fn.apply(this, arguments);
timer = true;
}, delay);
};
}
<button @click='btn'>按钮</button>
<script>
import {throttle} from "xxx"
export defalut{
methods:{
btn:throttle(function(){
console.log(123)
},1000)
}
}
<script setup>
const btn = throttle(()=>{
console.log(123)
},1000)
</script>