JS面试系列之防抖

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.怎么实现防抖?

// 第一版的防抖
// 当前getUserAction 的this 指向是window 
 oBody.addEventListener('mousemove', firstDebounce(getUserAction, 1000), false)
function firstDebounce(func, delay) {
    var timer = null;
    return function () {
        timer && clearTimeout(timer)
        timer = setTimeout(func, delay)
    }
}
// 第二版的防抖
// 尝试修改this指向 getUserAction不能传参
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)
    }
}
// 第三版的防抖
// 修改argments
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.平常开发的应用场景

搜索框输入关键字

频繁的点击按钮

监听浏览器滚动事件
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值