节流(最全 最干净 最好用)

文章讨论了浏览器中resize、scroll和touchmove等高频事件可能导致的页面卡顿问题,并提供了一个防抖函数的代码实现,用于优化事件处理,减少不必要的计算,提高页面性能。通过防抖技术,确保事件处理函数在特定时间间隔后只执行一次,有效解决了频繁触发导致的延迟和假死现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前因

浏览器中比较高频响应,resize/scroll/touchmove  响应函数复杂一些  会跟不上触发频率,便会出现页面卡顿,延迟,假死鞥现象

场景

搜索框查询

输入框联想

表单验证

提交按钮

代码实现(其实就是防抖稍微改动下触发事件罢了)

<!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>
        html {
            height: 100%;
        }
        body {
            display: flex;
            height: 100%;
            justify-content: center;
            align-items: center;
        }
        .box {
            width: 100px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            background: #FF9800;
            color: #fff;
        }
    </style>
</head>
<body>
    <div class="box">  0 </div>
    <script>
        const throttle = function (fun, delay) {
            let timeout
            return function() {            
                // timeout && clearTimeout(timeout)
                // 解决事件函数绑定中this
                let that = this
                // 绑定事件中 事件函数的传递
                let argus = arguments
                // timeout = setTimeout(() => {
                //   //fun.apply(that, argus)
                //   console.log('>>>>>>[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]', this) 
                //   fun(argus) 
                // }, delay);
                if (!timeout) {
                    timeout = setTimeout(() => {
                       fun.apply(that, argus) 
                       timeout = null
                    }, delay);
                }
            }
        }
        function fun(e) {
            count++
            console.log('>>>>>>>>>>>>', e, this)
            e.target.innerText = count
        }
        let count = 0
        document.querySelectorAll('.box')[0].addEventListener('mousemove', throttle((e) => {
            count++
            console.log('>>>>>>>>>>>>', e, this)
            e.target.innerText = count
        }, 1000))
    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值