js中防抖和节流区别
使用原因:
为防止用户频繁操作,导致页面卡顿,浏览器崩溃等情况,防抖和节流就是解决这种情况。
于一切眼中看见无所有,于无所希望中得救。
1.防抖
防抖可以看做是公交车司机等车站最后一个人上车后才出发
运用场景:
实时搜索(keyup),拖拽 (mousemove)
最主要要把时间清除
(本来想把代码贴出来的,就这样凑活一下吧。把笔记写在oneNode里了,发现从里面拷贝出来的全是图片 )
2.节流
节流可以看做火车在站台等待一定时间,时间到了就出发
运用场景:
窗口调整(resize),页面滚动(scroll),抢购疯狂点击(mousedown)
最主要给时间赋值null,timer = null;
代码(可测试):
<!DOCTYPE html>
<html>
<head>
<title>防抖、节流</title>
</head>
<body>
<button class="throttle">节流</button>
<button class="debounce">防抖</button>
</body>
<script>
function throttle(fn,wait){
let timer = null;
return function(){
let _this = this;
let args = arguments;
if(!timer){
timer = setTimeout(function(){
fn.apply(_this,args);
timer = null; //给时间赋值
},wait)
}
}
}
function debounce(fn,wait){
let timer = null;
return function(){
let _this = this;
let args = arguments;
clearTimeout(timer); //清除时间
timer = setTimeout(function(){
fn.apply(_this,args);
},wait)
}
}
function testThrottle(){
console.log("等待时间内,无论点击多少次都不触发,只有等待时间到了,才触发")
}
function testDebounce(){
console.log("无论点击多少次,最后一次点击才算,在等待时间后触发")
}
document.getElementsByClassName("throttle")[0].addEventListener('click',throttle(testThrottle,3000));
document.getElementsByClassName("debounce")[0].addEventListener('click',debounce(testDebounce,3000));
</script>
</html>
如果有不对的,欢迎指出!