防抖|节流

防抖(debounce): n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间

原理:
第一次调用函数,创建一个定时器,在指定的时间间隔之后运行代码。当第二次调用该函数时,它会清除前一次的定时器并设置另一个。如果前一个定时器已经执行过了,这个操作就没有任何意义。然而,如果前一个定时器尚未执行,其实就是将其替换为一个新的定时器,然后延迟一定时间再执行。并且使用一个布尔值( immediate)来控制第一次触发时是否立即执行。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>防抖</title>
</head>
<body>
<div id="content"
     style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:greenyellow;font-size:80px;"></div>
<script>
    let num = 1;
    let content = document.getElementById('content');

    function count() {
        content.innerHTML = num++;
    };
    content.onmousemove = debounce(count, 1000, true)

    function debounce(func, delay, immediate) {
        let timeout = null;
        return function () {
            let context = this;
            let args = arguments;

            if (timeout) clearTimeout(timeout);
            // 是否立即执行
            if(immediate && !timeout) {
                func.apply(context, args)
            }

            timeout = setTimeout(() => {
                func.apply(context, args)
            }, delay);
        }
    }
</script>
</body>
</html>

在这里插入图片描述
防抖的应用场景:

1.每次 resize/scroll 触发统计事件
2.文本输入的验证(连续输入文字后发送 AJAX 请求进行验证,验证一次就好)

节流(throttle): 高频事件在规定时间内只会执行一次,执行一次后,只有大于设定的执行周期后才会执行第二次。

原理:
用时间戳来判断是否已到执行时间,记录上次执行的时间戳,然后每次触发事件执行回调,回调中判断当前时间戳距离上次执行时间戳的间隔是否已经达到时间差 ,如果是则执行,并更新上次执行的时间戳,如此循环。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="content"
     style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:greenyellow;font-size:80px;">
</div>
<script>
    let num = 1;
    let content = document.getElementById('content');

    function count() {
        content.innerHTML = num++;
    };
    content.onmousemove = throttle(count, 1000)
    
     function throttle (fn, wait) {
        // 上一次执行 fn 的时间
        let previous = 0
        // 将 throttle 处理结果当作函数返回
        return function(...args) {
            // 获取当前时间,转换成时间戳,单位毫秒
            let now = +new Date()
            // 将当前时间和上一次执行函数的时间进行对比
            // 大于等待时间就把 previous 设置为当前时间并执行函数 fn
            if (now - previous > wait) {
                previous = now
                fn.apply(this, args)
            }
        }
    }
</script>

</body>
</html>

在这里插入图片描述
应用场景:
1.鼠标不断点击触发,mousedown(单位时间内只触发一次)
2.监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值