防抖
<body>
<!-- 防抖 场景:搜索框实时查询 当输入完成后1秒发起请求-->
<h2>防抖</h2>
<input placeholder="请输入内容" />
<script>
let telinput = document.querySelector("input")
telinput.addEventListener("input", debounce(dome, 1000))
// 封装一个防抖函数
function debounce(fn, delay) {
let timer = null
return () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(fn, delay)
}
}
// 监听input事件
function dome() {
console.log("发起请求")
}
</script>
</body>
节流
<body>
<!-- 节流 场景:连续点击按钮一秒只发送一次请求-->
<h2>节流</h2>
<button>点击发请求</button>
<script>
let btn = document.querySelector("button")
btn.addEventListener("click", throttle(dome, 1000))
// 封装一个节流函数
function throttle(fn, delay) {
let timer = null
return () => {
if (timer) {
return
}
timer = setTimeout(() => {
fn()
timer = null
}, delay)
}
}
// 监听click事件
function dome() {
console.log("发起请求")
}
</script>
</body>