防抖和节流

防抖

防抖触发高频率事件时n秒后只会执行一次,如果n秒内再次触发,则会重新计算。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>debounce防抖</title>
</head>
<body>
    <input type="text" id="search">
</body>
<script>
    // 防抖
    function debounce(func, delay) {
        let timer = null; 
        return function (...args) {
            // 清除原来定时器,重新设置新的定时器
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(this, args);
            }, delay);
        };
    }
    function search() {
        console.log("searching...");
    }
    const searchInput = document.getElementById('search');
    searchInput.addEventListener('input', debounce(search, 2000));
</script>
</html>

节流

高频事件触发,每次触发事件时设置一个延迟调用方法,并且取消之前的延时调用方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>throttle节流</title>
</head>
<body>
    <div style="height:3000px"></div>
</body>
<script>
    // 节流
    function throttle(func, delay) {
        let timer = null;
        return function (...args) {
            if (!timer) {
                timer = setTimeout(() => {
                    func.apply(this, args);
                    timer = null;
                }, delay);
            }
        };
    }
    // 使用节流优化滚动事件
    window.addEventListener('scroll', throttle(function () {
        console.log('scrolling...');
    }, 1000));
</script>
</html>```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值