zoukankan      html  css  js  c++  java
  • 防抖和节流

    实现防抖节流

    实现防抖

    概念: 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

    例子:如果有人进电梯,那电梯将在10秒钟后出发,这时如果又有人进电梯了,我们又得等10秒再出发。

    思路:通过闭包维护一个变量,此变量代表是否已经开始计时,如果已经开始计时则清空之前的计时器,重新开始计时。

    1.
    function debounce(fn, time) {
      let timer = null;
      return function () {
        let context = this  // 存储this指向
        let args = arguments   //可接收多个参数
        if (timer) {  、、开始timer是null,开始计时
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(function () {  //timer为记的时间
          fn.apply(context, args) //用apply使this指向调用者debounce ,这里是指向window
        }, time)
      }
    }
    
    window.onscroll = debounce(function(){
      console.log('触发:'+ new Date().getTime());
    },1000)
    
    2.
    function debounce(fn, time) {
      let timer = null;
      return function () {
        let context = this  // 存储this指向
        let args = arguments   //可接收多个参数
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(function () {
          fn.apply(context, args) //用apply使this指向调用者debounce ,这里是指向window
        }, time)  //时间到了触发test函数
      }
    }
    
    function test(name){
      console.log(name);  //打印‘zs’
      console.log(this); //this指向window, 如果是obj.newFn('zs')调用,this指向obj
    }
    let newFn = debounce(test,1000)
    window.onscroll = function () {
      newFn('zs')
      // obj.newFn('zs')
    }
    

    实现节流

    概念: 规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。

    例子:游戏内的技能冷却,无论你按多少次,技能只能在冷却好了之后才能再次触发

    思路:通过闭包维护一个变量,此变量代表是否允许执行函数,如果允许则执行函数并且把该变量修改为不允许,并使用定时器在规定时间后恢复该变量。

    1.
    function throttle(fn, time) {
      let canRun = true;
      return function () {
        if(canRun){
          fn.apply(this, arguments)  //apply刚好就收一个数组做参数  
          canRun = false
          setTimeout(function () {
            canRun = true
          }, time)
        }
      }
    }
    window.onscroll = throttle(function(){
      console.log('触发:'+ new Date().getTime());
    },1000)
    
    2.
    function throttle(fn,time) {
      let canRun = true  //是否允许fn执行
      return function () {
        if(canRun){
          fn.apply(this, arguments) //绑定this,解决传参的问题  把fn也就是test指向原this
          canRun = false
          setTimeout(function () {
            canRun = true
          },time)
        }
      }
    } 
    function test(name) {
      console.log(name);   //打印小明
      console.log(this.age);  //this指向obj  打印18
    }
    let obj  = {
      age:18
    }
    let newFn = throttle(test,1000)
    obj.newFn = newFn
    window.onscroll =function(){
      obj.newFn('小明')
    }
    
  • 相关阅读:
    事件(五):事件委托
    事件(四):事件类型
    【[ZJOI2005]午餐】
    【[POI2006]OKR-Periods of Words】
    【2^k进制数】
    【[SHOI2015]脑洞治疗仪】
    【[NOI2016]区间】
    【[SHOI2014]概率充电器】
    【逛公园】
    【[CQOI2014]数三角形】
  • 原文地址:https://www.cnblogs.com/xm0328/p/13977523.html
Copyright © 2011-2022 走看看