前言:函数防抖和函数节流都是用于优化高频率执行js的一种手段
节流
函数节流:是指一定时间内js方法只跑一次
应用场景:如resize,scroll在改变窗口和滚动的时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrap {
width: 200px;
height: 200px;
border: 1px solid red;
overflow-y: scroll;
margin-top: 50px;
}
.scroll {
height: 500px;
}
</style>
</head>
<body>
<div class="wrap" id="throttle">
<div class="scroll">函数节流</div>
</div>
</body>
</html>
<script>
let isPass = true;
let throttle = document.getElementById('throttle')
throttle.onscroll = () => {
if (!isPass) {
return;
}
isPass = false;
setTimeout(() => {
// 这里执行函数
console.log("函数节流")
isPass = true
}, 300);
}
</script>
ps:需要注意的是执行的间隔时间是>=300ms。如果具体执行的方法是包含callback的,也可以将isPass=true这一步放到callback中。
方法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
height: 2000px;
width: 300px;
background: pink;
}
</style>
</head>
<body>
<script>
// 节流:以第一个触发为准
const throttle = (fun,wait = 1500)=>{
// 固定时间触发一次
let lastTime = 0;
return function(...args){
let now = new Date();
if(now-lastTime>wait){
lastTime = now;
fun.apply(this,args);
}
}
}
window.onscroll= throttle(function(){
console.log("滚动")
})
</script>
</body>
</html>
防抖
函数防抖:是指频繁触发的情况下,只有足够的空闲时间,才执行代码一次(点击后一次动作时候会将前一次的给清空掉)
应用场景:如resize,scroll在改变窗口和滚动的时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrap {
width: 200px;
height: 200px;
border: 1px solid red;
overflow-y: scroll;
margin-top: 50px;
}
.scroll {
height: 500px;
}
</style>
</head>
<body>
<div class="wrap" id="debounce">
<div class="scroll">函数防抖</div>
</div>
</body>
</html>
<script>
let timer = null;
let debounce = document.getElementById('debounce')
debounce.onscroll = () => {
// 清除未执行的代码,重新执行动作
clearTimeout(timer);
timer = setTimeout(() => {
//这里执行函数
console.log('函数防抖')
}, 300);
}
</script>
方法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
height: 2000px;
width: 300px;
background: pink;
}
</style>
</head>
<body>
<script>
// 防抖,以最后一次为准(适用于用户在输入的时候进行优化)
const debounce = (fun,wait=50)=>{
// 缓存一个定时器id
let timer = 0;
return function(...args){
if (timer) clearTimeout(timer);
timer = setTimeout(()=>{
fun.apply(this,args);
},wait)
}
}
window.onscroll = debounce(function(){
console.log("防抖")
})
</script>
</body>
</html>