vue實現(xiàn)防抖、節(jié)流

防抖

指觸發(fā)事件后在 n 秒內(nèi)函數(shù)只能執(zhí)行一次,如果在 n 秒內(nèi)又觸發(fā)了事件,則會重新計算函數(shù)執(zhí)行時間

**js**
const debounce=function(fn, delay){
    let timer = null
    return function(){
        let content = this;
        let args = arguments;
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(()=>{
            fn.apply(content,args)
        }, delay)
    }
}
 
export default debounce
**使用**
import debounce from "@/common/debounce"
changeSeletc:debounce(function() {
      console.log('防抖:',this.serves)
 },500),
**VUE3**
import debounce from "@/common/debounce"
 const fn = debounce(function () {
      console.log("我是要執(zhí)行的函數(shù)");
  }, 1000);

節(jié)流

指連續(xù)觸發(fā)事件但是在 n 秒中只執(zhí)行一次函數(shù)。

**js**
const throttle=(func, delay) => {
    // 緩存一個定時器
    let timer = null
    // 這里返回的函數(shù)是每次用戶實際調(diào)用的節(jié)流函數(shù) 
    return function(...args) {
        if (!timer) { //判斷timer是否有值,如果沒有則說明定時器不存在即可繼續(xù)執(zhí)行
            timer = setTimeout(() => { //關
                func.apply(this, arguments)
                timer = null; //開
            }, delay)
        }
    }
}
export default throttle
**使用**
import throttle from "@/common/throttle"
methods:{
    submit:throttle(function()  {
        console.log('節(jié)流')
    },500)
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容