防抖
指觸發(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)
}