问题
什么是防抖和节流?有什么区别?如何实现?
- 防抖
触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
- 思路
每次触发事件时都取消之前的延时调用方法
<!--
* @Description: 防抖
* @Author: Jasper
* @Github: https://github.com/yuanxinfeng
* @Date: 2019-10-30 16:25:35
* @LastEditors: Jasper
* @LastEditTime: 2019-10-30 16:55:01
-->
<!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>test</title>
</head>
<body>
<input type="text" id="ipt" />
<ul id="sy"></ul>
</body>
<script>
let arr = new Array();
let index = 0;
let ipt = document.getElementById("ipt");
function debounce(_func_) {
// 创建一个标记用来存放定时器的返回值
let timeOut = null;
return function() {
// 每当用户输入的时候把前一个 setTimeout clear 掉
clearTimeout(timeOut);
// 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 _func_ 函数
setTimeout(() => {
_func_.apply(this, arguments);
}, 300);
};
}
function sayHi() {
index++;
console.log(`防抖成功${index}!!!`);
arr.push(`防抖成功${index}!!!`);
if (!ipt.value) clear();
sy();
}
function clear() {
arr = [];
}
function sy() {
let str = "";
arr.map((n, i) => {
str += `<li>${n}</li>`;
});
document.getElementById("sy").innerHTML = str;
}
ipt.addEventListener("input", debounce(sayHi));
</script>
</html>
- 节流
高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
- 思路
每次触发事件时都判断当前是否有等待执行的延时函数
<!--
* @Description: 节流
* @Author: Jasper
* @Github: https://github.com/yuanxinfeng
* @Date: 2019-10-30 17:01:25
* @LastEditors: Jasper
* @LastEditTime: 2019-10-30 17:28:55
-->
<!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>throttle</title>
<style>
* {
padding: 0;
margin: 0;
}
div{
padding: 10px;
margin: 10px;
}
</style>
</head>
<body>
<div>
<h1>宽:</h1>
<input type="text" id="cw" />
<h1>高:</h1>
<input type="text" id="ch" />
</div>
</body>
<script>
let cw = document.getElementById("cw");
let ch = document.getElementById("ch");
cw.value = document.body.clientWidth;
ch.value = document.body.clientHeight;
function throttle(_func_) {
let run = true;
return function() {
if (!run) return;
run = false;
setTimeout(() => {
_func_.apply(this, arguments);
run = true;
}, 300);
};
}
function sayHi(e) {
cw.value = e.target.innerWidth;
ch.value = e.target.innerHeight;
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener("resize", throttle(sayHi));
</script>
</html>
例子
自己可以贴下来跑一下
网友评论