JS高级中函数防抖和节流
一,介绍
在某些特定场景下,函数可能会被频繁的调用,回调中又会发生DOM操作,浏览器继而重排与重绘,造成很严重的性能问题。
二、使用步骤
函数防抖:
顾名思义,利用函数实现防抖动,触发函数时,元素的位置或者尺寸发生变化,导致页面回流,进而元素抖动,通过函数防抖,使得函数在一定时间内延迟执行一次,从而减少页面回流
<div class="box" id="boss">
1
</div>
// 短时间内多次触发同一事件,只执行最后一次,或者只执行最开始的一次,中间的不执行。
let num=1;
let boss=document.getElementById('boss');
//值得增长
function count(){
boss.innerHTML=num++;
}
boss.onmousemove=count;
最后一次执行
function debounce(func,times){
let timer;
return function(){
let boss=this;
let agres=arguments;//arguments中存在
if(timer)clearTimeout(timer);
timer=setTimeout(()=>{
func.apply(this,agres);
},times)
}
}
boss.onmousemove=debounce(count,1000);
立即执行
function debounce(func,times){
let timer;
return function(){
let boss=this;
let agres=arguments;// arguments中存着e
if(timer)clearTimeout(timer);
let callNow=!timer;
timer=setTimeout(()=>{
timer=null;
},times)
if(callNow)func.apply(this,agres);
}
}
函数节流:
限制函数执行的频率,如果当前函数未执行完毕,未来的执行都会被忽略
//时间戳版
function throttle(func, times) {
let previous = 0;
return function() {
let now = Date.now();
let boss = this;
let args = arguments;
if (now - previous > times) {
func.apply(boss, args);
previous = now;
}
}
}
boss.onmousemove=throttle(count,1000);
//定时器版
function throttle(func,times){
let timeout;
return function(){
let boss=this;
let agres=arguments;//arguments中存在
console.log(timeout);
if(!timeout){
timeout=setTimeout(()=>{
timeout=null;
func.apply(this,agres);
},times)
}
}
}
boss.onmousemove=throttle(count,1000);