防抖的两种实现方法

什么是防抖?

概念:函数防抖(debounce),就是指触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间。

例子:王者荣耀点击回城后,只有时间一到才会回到泉水。如果回城时被打断就只能重新计时回城的时间。

需求:

鼠标在盒子上移动,里面的数字就会变化。

法1.lodash库里的_.debounce(fun,时间)

参考链接:lodash库里的_.debounce(fun,时间)

<!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>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script src="./lodash.min.js"></script>
    <script>
        const box = document.querySelector('.box')
        let i = 1
        function mouseMove() {
            box.innerHTML = i++
        }
        box.addEventListener('mousemove', _.debounce(mouseMove, 500))
    </script>
</body>

</html>

法2:手写防抖函数

<!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>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        const box = document.querySelector('.box')
        let i = 1
        function mouseMove() {
            box.innerHTML = i++
        }
        // 核心是利用setTimeout定时器来实现
        // 1.声明定时器变量
        // 2.每次鼠标移动(事件触发)的时候要先判断是否有定时器,如果有先清除以前的定时器
        // 3.如果没有定时器,则开启定时器,存入到定时器变量里面
        // 4.定时器里面写函数调用
        function debounce(fn, t) {
            console.log(111);
            let timer
            // return一个匿名函数
            return function () {
                if (timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(function () {
                    fn()
                }, t)
            }
        }
        box.addEventListener('mouseover', debounce(mouseMove, 500))
    </script>
</body>

</html>

效果:

参考:黑马前端教程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值