<!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>深入js防抖与节流</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<h2>深入js防抖与节流</h2>
<input type="text" placeholder="请输入名称">
<div class="box"></div>
<script>
// 防抖 => 固定时间内,事件只允许发生一次
let nameInput = document.querySelector('input')
nameInput.addEventListener('input', antiShake(demo, 2000))
// 防抖封装
function antiShake(fn, wait) {
let timeOut = null;
return args => {
if (timeOut) clearTimeout(timeOut)
timeOut = setTimeout(fn, wait)
}
}
function demo() {
console.log('发起请求')
}
// 节流 => 保证一定时间内多个事件合并一个
// 应用场景 => 1、提交表单 2、高频监听事件
let box = document.querySelector(".box")
box.addEventListener("touchmove", throttle(demo, 2000))
function throttle(event, time) {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(() => {
event()
timer = null
}, time)
}
}
}
</script>
</body>
</html>