函数防抖和节流

前言:函数防抖和函数节流都是用于优化高频率执行js的一种手段

节流

函数节流:是指一定时间内js方法只跑一次
应用场景:如resize,scroll在改变窗口和滚动的时候

<!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>
  <style>
    .wrap {
      width: 200px;
      height: 200px;
      border: 1px solid red;
      overflow-y: scroll;
      margin-top: 50px;
    }

    .scroll {
      height: 500px;
    }
  </style>
</head>

<body>
  <div class="wrap" id="throttle">
    <div class="scroll">函数节流</div>
  </div>
</body>

</html>
<script>
  let isPass = true;
  let throttle = document.getElementById('throttle')
  throttle.onscroll = () => {
    if (!isPass) {
      return;
    }
    isPass = false;
    setTimeout(() => {
      // 这里执行函数
      console.log("函数节流")
      isPass = true
    }, 300);
  }
</script>
ps:需要注意的是执行的间隔时间是>=300ms。如果具体执行的方法是包含callback的,也可以将isPass=true这一步放到callback中。

方法二:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
      body{
          height: 2000px;
          width: 300px;
          background: pink;
      }
  </style>
</head>
<body>

  <script>
      // 节流:以第一个触发为准
      const throttle = (fun,wait = 1500)=>{
          // 固定时间触发一次
          let lastTime = 0;
          return function(...args){
              let now = new Date();
              if(now-lastTime>wait){
                  lastTime = now;
                  fun.apply(this,args);
              }
          }
      }
      window.onscroll= throttle(function(){
          console.log("滚动")
      })
  </script>
</body>
</html>


防抖

函数防抖:是指频繁触发的情况下,只有足够的空闲时间,才执行代码一次(点击后一次动作时候会将前一次的给清空掉)
应用场景:如resize,scroll在改变窗口和滚动的时候

<!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>
  <style>
    .wrap {
      width: 200px;
      height: 200px;
      border: 1px solid red;
      overflow-y: scroll;
      margin-top: 50px;
    }

    .scroll {
      height: 500px;
    }
  </style>
</head>

<body>
  <div class="wrap" id="debounce">
    <div class="scroll">函数防抖</div>
  </div>
</body>

</html>
<script>
  let timer = null;
  let debounce = document.getElementById('debounce')
  debounce.onscroll = () => {
    // 清除未执行的代码,重新执行动作
    clearTimeout(timer);
    timer = setTimeout(() => {
      //这里执行函数
      console.log('函数防抖')
    }, 300);
  }
</script>

方法二:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            height: 2000px;
            width: 300px;
            background: pink;
        }
    </style>
</head>
<body>

    <script>
       // 防抖,以最后一次为准(适用于用户在输入的时候进行优化)
        const debounce = (fun,wait=50)=>{
            // 缓存一个定时器id
            let timer = 0;
            return function(...args){
                if (timer) clearTimeout(timer);
                timer = setTimeout(()=>{
                    fun.apply(this,args);
                },wait)
            }
        }
        window.onscroll = debounce(function(){
                console.log("防抖")
            })
    </script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在前端开发的过程中,我们经常会需要绑定一些持续触发的事件,如 resize、scroll、mousemove 等等...
    淘淘笙悦阅读 226,671评论 42 349
  • 一、什么是函数节流 函数节流:是确保函数特定的时间内至多执行一次。 1.函数节流的原理 函数节流的原理挺简单的,当...
    it之承影含光阅读 564评论 2 1
  • 概念 函数防抖(debounce) 当调用动作过n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执...
    yuanjiex阅读 646评论 0 1
  • 前言 最近和前端的小伙伴们,在讨论面试题的时候。谈到了函数防抖和函数节流的应用场景和原理。于是,想深入研究一下两者...
    youthcity阅读 23,663评论 5 78
  • 向遗体告别 文/张波 天津 20170713 1.我怎么如此幸运特别意想不到晚上回到宿舍,博杰见我说“好像我不认识...
    能量波阅读 227评论 0 2