关于scroll 节流 和 防抖的疑惑

今天研究了一下scroll 的节流 和 防抖,写了一个demo,最后发现被触发的顺序改变了,但是被触犯的次数都是69,既然被触发的次数都相同请问节流和防抖到底有什么意义呢?代码如下

<template>
  <div class="container" style="height: 667px;">
    <div class="content" style="height: 3000px"></div>
    <a href="javascript: void(0)" 
        @click="_getNum"
        style="color: blue; font-size: 20px;"
    >点击</a>
  </div>
</template>

export default {
  data(){
    return {
      a: 0,
      b: 0,
      c: 0
    }
  },
  mounted(){
    var container = document.getElementsByClassName('container')[0]
    container.addEventListener('scroll', () => {
      this.a++
      this.debounce(() => {
        this.b++
      }, 250)
      this.throttling(() => {
        this.c++
      }, 500, 1000)
    })
  },
  methods: {
    _getNum(){
      console.log(this.a, this.b, this.c)
    },
    // 防抖
    debounce(func, wait, immediate) {
      var timeout
      return function(){
          var context = this,
              args = arguments
          var later = function(){
              timeout = null
              if(!immediate){
                  func.apply(context, args)
              }
          }
          var callNow = immediate && !timeout
          clearTimeout(timeout)
          timeout = setTimeout(later, wait)
          if(callNow){
              func.apply(context, args)
          }
      }()
    },
    // 节流
    throttling(fn, wait, maxTimelong) {
      var timeout = null,
          startTime = Date.parse(new Date);
      return function() {
          if(timeout !== null) clearTimeout(timeout);
          var curTime = Date.parse(new Date);
          if(curTime-startTime>=maxTimelong) {
              fn() && (startTime = curTime)
          } else {
              timeout = setTimeout(fn, wait);
          }
      }()
    }
  }
}

然后滚动浏览器,结果如下

clipboard.png

阅读 2k
1 个回答

用法不对,代码也不对

function fn(){
    var timer
    return function(){}()
}

你返回的是undefined,调用时每次fn()都从新生成一个timer
你的节流跟防抖跟普通函数没有区别

function fn(callback, time) {
    var timer = null;
    return function (...arg) {
        var $this = this;
        clearTimeout(timer);
        timer = setTimeout(function () {
            callback.apply($this,arg);
        }, time)
    }
}

var a = 1;
var fn1 = fn(function(){
    a++
},1);

fn1();
fn1();
fn1();
fn1();
fn1();
fn1();
fn1();
fn1();
fn1();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题