Vue-cli组件中写一个节流函数

节流:多次触发同一个事件,但是n秒之后才执行一次函数,如果n秒之后再次触发,那么将会重新计算执行函数的时间,节流函数无疑能够减少性能的消耗。

1.在data中定义一个timer

data(){
  return {
    timer:null
  }
},

2.在methods中写函数

throttle(wait){
  return ()=>{
    if(this.timer){
      console.log('timer:'+this.timer)
      clearTimeout(this.timer)
    }
    this.timer = setTimeout(()=>{this.printer();
    },wait)
  }
},

3.写一个要执行的方法,比如打印

printer(){console.log('1234');
},

4.接下来,在触发事件的时候,调用下方法就行,比如点击的时候执行 throttle(2000)()

节流函数原理:触发事件的时候,判断上一次定时器的返回值,如果有,就清除掉,在规定的时间内,没有清除定时器,就会执行我们的目标函数

猜你喜欢

转载自www.cnblogs.com/luyuandatabase/p/12715977.html
今日推荐