JS中的防抖和节流

为什么要用到防抖和节流

前端代码的执行是基于浏览器的,频繁的进行某些计算或处理会占用更多的内存和CPU时间,可能会导致浏览器挂起,甚至是崩溃。

防抖和节流即是为了限制JS频繁的执行一段代码

防抖节流的定义及区别

防抖
连续的多次触发,固定的时间间隔内,存在新的触发,就清除之前的重新记时,满足时间执行一次——最新一次触发

节流
连续的多次触发,每一段固定的时间间隔内,我们只去执行一次——固定频率触发

图说
在这里插入图片描述

常见的应用场景

频繁操作dom,发送请求

视图窗口变化
window的 resize
键盘事件
文字输入时的 keyup 事件
鼠标事件
元素拖拽、移动时的 mousemove 事件;
按钮的不断点击;
滚轮滚动scroll 事件

各自的函数实现

防抖函数

/**
 *fn:真正需要执行的函数
 *delay:延时时间
 */
function debounce(fn, delay) {
  var timer = null;
  //这里使用闭包,方便我们自定义一些内部数据
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      //使用apply确保方法在适当的环境中执行
      fn.apply(this,args);
    }, delay);
  }
}

节流函数

/**
 *fn:真正需要执行的函数
 *delay:延时时间
 */
function throttle(fn, delay){
   var last = null,
   return function () {
      const now = + Date.now()
      if(now > last + delay){
      	 last = now
      	 fn.apply(this,args)
      }	  
   }
}

实例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>函数防抖节流</title>
</head>
<style>
    .mytest{
        width: inherit;
        height: 200px;
        background-color: antiquewhite;
        align-items: center;
        font-size: 50px;
        display: flex;
        justify-content: center;
    }
</style>
<body>
    <div class="mytest" >0</div>
</body>
<script>
    function debounce(fn, delay) {
      var timer = null;
      return function () {
        if (timer) clearTimeout(timer);
        var _this = this;
        var _arguments = arguments;
        timer = setTimeout(function () {
          fn.apply(_this,_arguments);
        }, delay);
      }
    }
    function throttle(fn, delay){
       var timer = null,
       booleanVal = false;
       return function () {
            if (booleanVal) {
              return 
            } 
            booleanVal = true;
            var _this = this;
            var _arguments = arguments;
            timer = setTimeout(function() {
                fn.apply(_this,_arguments);
              booleanVal = false;
            },delay)
        }
    }
    var div = document.querySelector('.mytest');
    function foo() {
        div.innerHTML = ++foo.count; 
    }
    foo.count = 0;
    div.onmousemove = throttle(foo,500);
</script>
</html>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值