1.什么是防抖?
答:防抖是针对响应跟不上触发频率这类问题的一种解决方案(另一种是节流)。
2.为什么需要防抖?
答:一些高频的函数操作比如resize,input,scroll, mousemove可能产生不好的影响,例如事件执行一次就要调用一次ajax。
<!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>debounce</title>
</head>
<style>
#box {
width: 100%;
height: 300px;
background-color: #eee;
color: red;
font-size: 30px;
text-align: center;
font-weight: 700;
line-height: 300px;
}
</style>
<body>
<div id="box"></div>
<script>
var count = 1;
var oBody = document.getElementById('box');
function getUserAction() {
oBody.innerHTML = count++;
}
oBody.addEventListener('mousemove', getUserAction, false)
</script>
</body>
</html>
3.防抖的原理是什么?
答:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
4.怎么实现防抖?
oBody.addEventListener('mousemove', firstDebounce(getUserAction, 1000), false)
function firstDebounce(func, delay) {
var timer = null;
return function () {
timer && clearTimeout(timer)
timer = setTimeout(func, delay)
}
}
oBody.addEventListener('mousemove', secondDebounce(getUserAction, 1000), false)
function secondDebounce(func, delay) {
let timer = null;
return function() {
let context = this;
timer && clearTimeout(timer)
timer = setTimeout(() => {
func.apply(context)
},delay)
}
}
oBody.addEventListener('mousemove', thirdDebounce(getUserAction, 1000), false)
function thirdDebounce(func, delay) {
let timer = null
return function () {
let context = this
let args = arguments
timer && clearTimeout(timer)
timer = setTimeout(() => {
func.apply(context, args)
}, delay)
}
}
5.平常开发的应用场景
搜索框输入关键字
频繁的点击按钮
监听浏览器滚动事件