防抖的应用场景:某个时间段内只执行最后1次,比如输入框搜索推荐
节流的应用场景:某个时间段内只执行第一次,例如登录、表单提交
<!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" placeholder="请输入搜索的关键词">
<button>提交</button>
<script type="text/javascript">
let input = document.querySelector("input");
let button = document.querySelector("button");
// 防抖
input.oninput = anti_shake(post, 500);
// 节流
button.onclick = reduce_float(post, 500);
function post() {
console.log("请求" + input.value);
}
function anti_shake(f, timeout) {
let t = null;
return function() {
if (t !== null) {
clearTimeout(t);
}
t = setTimeout(f, timeout);
}
}
function reduce_float(f, timeout) {
let t = null;
return function() {
if (t !== null) {
clearTimeout(t);
}
t = setTimeout(() => {
f();
t = null;
}, timeout);
}
}
</script>
</body>
</html>