Ajax:什么是防抖? --- 面试高频题

什么是防抖?
在一段时间内频繁触发某个事件,只会执行最后一次,也就是说将多次触发变成了一次触发

防抖的好处
避免频繁的调用服务器资源,给服务器带来压力

代码示范:

/* css样式 */
<style>
        input {
            width: 200px;
            height: 25px;
            outline: none;
            border: 1px solid skyblue;
        }

        button {
            width: 50px;
            height: 28px;
            background-color: skyblue;
            border: none;
            cursor: pointer;
        }
</style>

<!-- body中的代码 -->
<body>
    <input type="text">
    <button>提交</button>
    <script>
    	// 获取元素
        let btn = document.querySelector('button')
        let count = 0
        // 如果频繁点击btn按钮,会被触发很多次
        // 要限制触发的频率,比如:如果是在300毫秒内重复点击了btn,那么则不去执行count++
        btn.addEventListener('click', function () {
            clearTimeout(this.timerId) // 只要是在300毫秒内频繁点击了按钮,都不会执行
            // this.timerId 表示当前浏览器的一个标识
             this.timerId = setTimeout(function () {
                count++
                console.log(`我被点击了${count}次`)
            }, 300)
        })
    </script>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值