原文:https://blog.csdn.net/weixin_42735794/article/details/91388550
函數防抖
定義:多次觸發事件后,事件處理函數只執行一次,並且是在觸發操作結束時執行。
在vue中對click添加防抖處理
const on = Vue.prototype.$on // 防抖處理 Vue.prototype.$on = function (event, func) { let timer let newFunc = func if (event === 'click') { newFunc = function () { clearTimeout(timer) timer = setTimeout(function () { func.apply(this, arguments) }, 500) } } on.call(this, event, newFunc) }
函數節流
定義:觸發函數事件后,短時間間隔內無法連續調用,只有上一次函數執行后,過了規定的時間間隔,才能進行下一次的函數調用。
在vue中對click添加節流處理
const on = Vue.prototype.$on // 節流 Vue.prototype.$on = function (event, func) { let previous = 0 let newFunc = func if (event === 'click') { newFunc = function () { const now = new Date().getTime() if (previous + 1000 <= now) { func.apply(this, arguments) previous = now } } } on.call(this, event, newFunc) }