防抖、节流

防抖

防抖是指在一段连续的时间内,只执行最后一次触发的操作。如果在这段时间内事件被再次触发,计时会被重置。防抖适用于需要在事件停止触发一段时间后执行操作的情况,例如搜索框输入,以避免在用户仍在输入时频繁触发搜索请求。

节流

节流是指在一段时间内,以固定的频率执行操作,无论事件触发多少次。节流适用于需要限制事件处理的频率,以确保操作不会过于频繁,例如滚动加载,以避免在滚动过程中加载过多的内容。

防抖适用于确保只有事件停止触发后才执行操作,而节流适用于以固定频率执行操作,以平稳处理高频事件。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset='utf-8' />
    <meta name='viewport' content='width=device-width, initial'>
    <title>防抖</title>
    <style>

    </style>
</head>

<body>
    <div>
        <button onclick="antiShake()">
            防抖
        </button>
        <button onclick="throttle()">
            节流
        </button>
    </div>
    <script>
        let timeout = null
        let btn = document.querySelector("button")
        btn.addEventListener('click', () => {
                clearTimeout(timeout)
                timeout = setTimeout(() => {
                    console.log('antiShake')
                }, 3 * 1000)
            })
            // antiShake = function() {
            //     clearTimeout(timeout)
            //     timeout = setTimeout(() => {
            //         console.log('antiShake')
            //     }, 1000 * 8)
            // }

        function throttle(fn) {
            let canRun = true // 通过闭包保存一个标记
            return function() {
                if (!canRun) return
                    // 在函数开头判断标记是否为 true, 不为 true 则 return
                canRun = false // 立即设置为 false
                setTimeout(() => {
                    // 将外部传入的函数的执行放在 setTimeout 中
                    fn.apply(this, arguments)
                        // 最后在 setTimeout 执行完毕后再把标记设置为 true(关键) 表
                        // 示可以执行下一次循环了。 当定时器没有执行的时候标记永远是 false, 在开头
                        // 被return 掉
                    canRun = true
                }, 500)
            }
        }

        function sayHi(e) {
            console.log(e.target.innerWidth,
                e.target.innerHeight)
        }
        window.addEventListener('resize',
            throttle(sayHi))
    </script>
</body>

</html>```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值