js的函数防抖与函数节流

做了一个小例子,深入的了解函数节流与防抖的区别

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
   <input type="text" id="inp">
</body>
<script>
    //  利用函数防抖 搜索功能,在0.5秒内只执行最后一次,如果在规定的时间内又触发了事件定时器则会重新计算
          function debounce(fn) {
           var timer = null;
           return function () {
               clearTimeout(timer)
               timer = setTimeout(() => {
                   fn.apply(this)
               }, 500)
           }
       }
       function say() {
           console.log("成功了")
       }
       document.querySelector("#inp").addEventListener("keydown", debounce(say))    

        // 监听改变窗口大小,在规定的时间内只计算一次
        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>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值