鍍金池/ 問(wèn)答/HTML/ 關(guān)于scroll 節(jié)流 和 防抖的疑惑

關(guān)于scroll 節(jié)流 和 防抖的疑惑

今天研究了一下scroll 的節(jié)流 和 防抖,寫(xiě)了一個(gè)demo,最后發(fā)現(xiàn)被觸發(fā)的順序改變了,但是被觸犯的次數(shù)都是69,既然被觸發(fā)的次數(shù)都相同請(qǐng)問(wèn)節(jié)流和防抖到底有什么意義呢?代碼如下

<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;"
    >點(diǎn)擊</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)
          }
      }()
    },
    // 節(jié)流
    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);
          }
      }()
    }
  }
}

然后滾動(dòng)瀏覽器,結(jié)果如下

clipboard.png

回答
編輯回答
維她命

用法不對(duì),代碼也不對(duì)

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

你返回的是undefined,調(diào)用時(shí)每次fn()都從新生成一個(gè)timer
你的節(jié)流跟防抖跟普通函數(shù)沒(méi)有區(qū)別

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();
2018年6月21日 22:20