节流:常用于窗口的缩放,滚动条下拉;
防抖:常用于input框输入搜索
以下是vue中的使用方法:
工具common.js中:
//节流
export function throttle(fn,time = 500){
let run = true;
return function(){
if(!run) return;
run = false;
setTimeout(()=>{
fn.apply(this,arguments);
run = true;
},time)
}
}
//防抖
export function debounce(fn,time = 500){
let timeName = null;
return function(){
clearTimeout(timeName);
timeName = setTimeout(()=>{
fn.apply(this,arguments);
},time)
}
}
vue中引用:
import {throttle,debounce} from '@/utils/common';
methods:{
throttle:throttle(()=>{
console.log(`节流`)
},1000),
debounce:debounce(()=>{
console.log('防抖')
},1000)
}