防抖和节流都是一种性能优化的手段,也可使用现成的工具库lodash,lodash是对各种方法、函数的封装,具体查看官网 https://www.lodashjs.com/docs/lodash.assign
使用方法
1、npm 下载 lodash npm install lodash
2、按需引入防抖或节流 import { debounce } from 'lodash';
3、使用
handleInput: debounce(function (val) {
console.log(val)
}, 200)
如果不用现成工具,可自己手写
1、防抖函数 (多次触发 只执行最后一次)
应用场景:
输入框中频繁的输入内容,搜索;
频繁的点击按钮,发送了多次请求;
监听浏览器滚动事件,完成某些特定操作;
用户缩放浏览器的resize次数过于频繁,造成计算过多。
function debounce(fun,wait){
let timer = null;
return function(){
if(timer) clearTimeout(timer);
let args = arguments;
timer=setTimeout(()=>{
fun.apply(this,args);//用apply改变this指向
},wait)
}
}
2、节流函数 (规定时间内 只触发一次)
应用场景:
鼠标移动事件;
滑动验证码滑块时;
监听页面的滚动事件,比如是否滑到底部自动加载更多;
用户频繁点击按钮操作,规定时间内 只触发一次。
// 方式1: 使用时间戳
function throttle1(fn, wait) {
let time = 0;
return function() {
let args = arguments;
let now = Date.now()
if(now - time > wait) {
fn.apply(this, args);//用apply改变this指向
time = now;
}
}
}
// 方式2: 使用定时器
function thorttle2(fn, wait) {
let timer;
return function () {
let args = arguments;
if(!timer) {
timer = setTimeout(function(){
timer = null;
fn.apply(this, args);//用apply改变this指向
}, wait)
}
}
}