性能优化这个领域的很多内容都很碎片化,比如对图片方面的优化(计算图片的大小、图片加载优化)、DNS解析、CDN加载、预解析、懒执行,包括今天要总结的防抖和节流。就算你没听过防抖节流,但是你做项目的时候,一定遇到过。如果你知道了这块知识,那么你之前的问题就迎刃而解了。
防抖
我们先来看下没有防抖的情况,也就是平时我们知道,但是没想到优化、或者不知道怎么优化的
- 没有防抖
function ajax(content){
console.log('ajax requset' + content);
}
let inputa = document.getElementById('unDebounce');
inputa.addEventListener('keyup', function(e){
ajax(e.target.value);
})
总结: 没有防抖的情况下,只要按下键盘,就会发起请求
2.优化,加上防抖
function debounce(fun, delay){
return function(args){
let that = this;
clearTimeout(fun.id);
fun.id = setTimeout(function(){
fun.call(that, args);
}, delay)
}
}
// or
let debounce1 = (func, delay) => {
let timer = null;
return function(...args){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args)
timer = null
}, delay)
}
}
let inputb = document.getElementById('debounce');
let debounceAjax = debounce1(ajax, 3000);
inputb.addEventListener('keyup', function(e){
debounceAjax(e.target.value);
})
总结: 当你在频繁的输入时,并不会发送请求,只有当你在指定的间隔内,没有输入时,才会执行函数。
如果停止输入但是在指定的间隔内又输入,会重新触发计时。
即: 一定时间连续触发,只在最后一次执行
- 场景
- search搜索联想,用户不断输入值,用防抖来节约请求
- window触发resize的时候,不断地调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
节流
1.节流
throttle (fn, wait) {
let timer = null
return function () {
if (timer) {
return
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null;
}, wait)
}
},
const throttle1 = (func, wait = 50) => {
let previous = 0;
return function(...args){
let now = new Date();
if(now - previous > wait){
func.apply(this, args);
previous = now;
}
}
}
let inputc = document.getElementById('throttle');
let throttleAjax = throttle1(ajax, 1000);
inputc.addEventListener('keyup', function(e){
throttleAjax(e.target.value)
})
总结:节流是一段时间内只执行一次,即每隔一定时间执行一次
- 场景
- 鼠标不断点击
- 监听滚动事件