概要
防抖:先放你走,如果有新的人来了,再把你叫回来。(先用setTimeout让函数在一段时间后执行,如果有新的事件进来了,就杀死之前的timer),特点是杀死先触发的事件。
节流:你是动物园的饲养员,有很多人要给兔子喂胡萝卜(可能争先恐后的哦),你的策略是等吃完了上一根才允许下一个人继续给胡萝卜。(当已经在setTimeout执行了一个函数,就把开关关闭。函数执行完之后,记得把开关打开。)特点是杀死后触发的事件。
防抖demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
background: #ccc;
width: 1000px;
height: 500px;
text-align: center;
line-height: 500px;
font-size: 5rem;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
const debounce =(func, delay)=> {
let timer = null;
return function(...rest){
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, rest);
}, delay);
}
}
document.getElementById("box").onmousemove = debounce(function (e) {
this.innerHTML = `${e.clientX}-${e.clientY}`
}, 50)
</script>
</body>
</html>
节流demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
background: #ccc;
width: 1000px;
height: 500px;
text-align: center;
line-height: 500px;
font-size: 5rem;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
function throttle(func, delay) {
let flag = true;
return function(...rest) {
if(!flag){
return ;
}
flag = false;
setTimeout(() =>{
func.apply(this,rest);
flag = true;
},delay);
}
}
document.getElementById("box").onmousemove = throttle(function (e) {
this.innerHTML = `${e.clientX}-${e.clientY}`
}, 500)
</script>
</body>
</html>
综合版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
background: #ccc;
width: 1000px;
height: 500px;
text-align: center;
line-height: 500px;
font-size: 5rem;
}
</style>
</head>
<body>
<select id="select">
<option value="audi">防抖</option>
<option value="volvo">节流</option>
<option value="mst">不加入防抖和节流</option>
</select>
<div id="box"></div>
<script>
const debounce = (func, delay) => {
console.log('debounce');
let timer = null;
return function (...rest) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, rest)
}, delay);
}
}
function throttle(func, delay) {
console.log('throttle');
let flag = true;
return function (...rest) {
if (flag) {
flag = false;
setTimeout(() => {
func.apply(this, rest);
flag = true;
}, delay);
}
}
}
function pure(func){
return function(...rest){
func.apply(this,rest);
}
}
const option = [debounce, throttle,pure];
// 业务
var box = document.getElementById("box");
var myselect = document.getElementById("select");
var index = myselect.selectedIndex;
const main = () => {
box.onmousemove = option[index](function (e) {
this.innerHTML = `${e.clientX}-${e.clientY}`
}, 50)
}
myselect.addEventListener('change', function () {
index = myselect.selectedIndex;
main();
}, false)
main();
</script>
</body>
</html>
tips
@wx:qq981145483