关于防抖和节流我的一些理解

防抖和节流会造成什么样的影响?

连续触发的事件会对造成服务器压力过大,或者内存占用过多,可以使用防抖和节流来缓解。

什么是防抖?

防抖就是指连续触发的事件,在n秒钟之后在执行回调,如果n秒钟之内又触发了事件,那么就是重新计算。

使用场景:
	比如表单提交按钮

防抖代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    *{padding:0;margin:0;}
    .scroll-box{
        width : 100%;
        height : 500px;
        background:blue;
        overflow : auto;
    }    
    .scroll-item{
        height:1000px;
        width:100%;
        /* background-color: green; */
    }
    </style>
<body>
    <div class="scroll-box">
        <div class="scroll-item"></div>
    </div>
</body>
<script>
let debounce = function (fn, wait) {
    let timeout = null;
    return function () {
      if (timeout !== null) clearTimeout(timeout);//如果多次触发将上次记录延迟清除掉
      timeout = setTimeout(() => {
        fn.apply(this, arguments);
        // 或者直接 fn()
        timeout = null;
      }, wait);
    };
}
     // 处理函数
  function handle() {
    console.log(arguments)
    console.log(Math.random());
  }
  // 测试用例
  document.getElementsByClassName('scroll-box')[0].addEventListener("scroll", debounce(handle, 3000));
</script>
</html>

什么是节流?

节流指连续触发的事件,在n秒内必会执行一次。

使用场景:
	用户下拉刷新列表的时候,用节流比防抖要好

节流代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    *{padding:0;margin:0;}
    .scroll-box{
        width : 100%;
        height : 500px;
        background:blue;
        overflow : auto;
    }    
    .scroll-item{
        height:1000px;
        width:100%;
        /* background-color: green; */
    }
</style>
<body>
    <div class="scroll-box">
        <div class="scroll-item"></div>
    </div>
</body>
<script>
let settime = (func,howtime)=>{
    let timers = null
    return ()=>{
        if(!timers){
            timers = setTimeout(() => {
                // func.apply(this,arguments)
                func()
                timers = null           
            },howtime);
        }
    }
}

function handle(){
    console.log(arguments);
    console.log(Math.random());
}

document.getElementsByClassName("scroll-box")[0].addEventListener("scroll",settime(handle,2000))   
</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值