防抖和节流会造成什么样的影响?
连续触发的事件会对造成服务器压力过大,或者内存占用过多,可以使用防抖和节流来缓解。
什么是防抖?
防抖就是指连续触发的事件,在n秒钟之后在执行回调,如果n秒钟之内又触发了事件,那么就是重新计算。
使用场景:
比如表单提交按钮
防抖代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{padding:0;margin:0;}
.scroll-box{
width : 100%;
height : 500px;
background:blue;
overflow : auto;
}
.scroll-item{
height:1000px;
width:100%;
}
</style>
<body>
<div class="scroll-box">
<div class="scroll-item"></div>
</div>
</body>
<script>
let debounce = function (fn, wait) {
let timeout = null;
return function () {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, arguments);
timeout = null;
}, wait);
};
}
function handle() {
console.log(arguments)
console.log(Math.random());
}
document.getElementsByClassName('scroll-box')[0].addEventListener("scroll", debounce(handle, 3000));
</script>
</html>
什么是节流?
节流指连续触发的事件,在n秒内必会执行一次。
使用场景:
用户下拉刷新列表的时候,用节流比防抖要好
节流代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{padding:0;margin:0;}
.scroll-box{
width : 100%;
height : 500px;
background:blue;
overflow : auto;
}
.scroll-item{
height:1000px;
width:100%;
}
</style>
<body>
<div class="scroll-box">
<div class="scroll-item"></div>
</div>
</body>
<script>
let settime = (func,howtime)=>{
let timers = null
return ()=>{
if(!timers){
timers = setTimeout(() => {
func()
timers = null
},howtime);
}
}
}
function handle(){
console.log(arguments);
console.log(Math.random());
}
document.getElementsByClassName("scroll-box")[0].addEventListener("scroll",settime(handle,2000))
</script>
</html>