vue之防抖节流

82 阅读1分钟
  • 防抖是触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
  • 节流是高频事件触发,但在n秒内只会执行一次,如果n秒内触发多次函数,只有一次生效
//js文件

//防抖
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);
  };
}
//vue文件

<button @click='btn'>按钮</button>


//Vue2用法
<script>
import {throttle} from "xxx"
export defalut{


methods:{
        btn:throttle(function(){
        console.log(123)
        },1000)
    }
}


//Vue3用法

<script setup> 

const btn = throttle(()=>{
    console.log(123)
},1000)
</script>