用代码实现防抖和节流

防抖

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

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

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

function debounce(fn, time) {
  let timer = null;
  return function () {
    let context = this
    let args = arguments
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, time)
  }
}
window.onscroll = debounce(function(){
  console.log('触发:'+ new Date().getTime());
},1000)

节流

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

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

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

function throttle(fn, time) {
  let canRun = true;
  return function () {
    if(canRun){
      fn.apply(this, arguments)
      canRun = false
      setTimeout(function () {
        canRun = true
      }, time)
    }
  }
}
window.onscroll = throttle(function(){
  console.log('触发:'+ new Date().getTime());
},1000)

猜你喜欢

转载自www.cnblogs.com/wtsx-2019/p/12615038.html
今日推荐