<!DOCTYPE html>
<html lang="zh">
<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: 100%;
width: 100%;
background-color: pink;
}
</style>
</head>
<body>
</body>
<script>
(() => {
// 防抖 其实就是 在最后一次执行的时候才开始运行
const fangDou = (fun, time) => { //表示在time时间内fun函数不会再次触发,之后触发最后一次
let timer = null;
return () => {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fun();
}, time)
}
}
// 节流 就是在该动作中,间隔相同的时间运行一次,也就是在time时间内最多只有一个fun函数运行
const jieLiu = (fun, time) => {
let timer = null;
return () => {
if(timer) {
return ;
}
timer = setTimeout(() => {
fun();
timer = null;
}, time)
}
}
// 防抖
window.addEventListener('resize', fangDou((e) => {
console.log('fangDou')
}, 500))
// 节流
window.addEventListener('resize', jieLiu((e) => {
console.log('jieLiu')
}, 500))
})()
</script>
</html>
08-31
281
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
02-10
68
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
03-03
4048
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)