一、防抖和节流的意义
- 防抖(Debounce)和节流(Throttle)都是用来控制某个函数在一定时间内触发次数,两者都是为了减少触发频率,以便提高性能或者说避免资源浪费。
- 防抖: n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
- 举例:电梯第一个人进来后,等待15秒。如果过程中又有人进来,15秒等待重新计时,直到15秒后开始运送,这是防抖
- 节流: n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效
- 举例:电梯第一个人进来后,15秒后准时运送一次,这是节流
二、防抖
防抖: n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
代码:
<!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>防抖</title>
</head>
<body>
<input type="text"/>
</body>
</html>
<script>
// 防抖函数,频繁事件执行时,只执行最后一次事件
let inp=document.querySelector("input");
inp.oninput=debounce(function(){
console.log(this.value);
},500)
function debounce(fn,delay){
let t=null;
return function(){
if(t!==null){
clearTimeout(t);
}
t=setTimeout(()=>{
fn.call(this);
},delay)
}
}
</script>
三、节流
节流:n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效
<!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>节流</title>
<style>
body{
height:3000px;
}
</style>
</head>
<body>
</body>
</html>
<script>
window.onscroll=throttle(function(){
console.log("hello world");
},500)
//节流函数
function throttle(fn,delay){
let flag=true;
return function(){
if(flag){
setTimeout(()=>{
fn.call(this);
flag=true;
},500)
}
flag=false;
}
}
</script>