标签:按钮 执行 场景 net 搜索 app block als 大小
限制一个函数在一定时间内只能执行一次。忽略在当前时间段内其他的事件触发。
let canPushToStack = true;
window.addEventListener('scroll',function(){
    canPushToStack = false;
    setTimeout(function(){
        console.log('我滚动了');
        canPushToStack = true;
    },1000)
})function throttle(func, wait) {
  let canStack = true;
  return function (...rest) {
    if (canStack) {
      setTimeout(() => {
        func.apply(this, rest);
        canStack = true
      }, wait);
    }
    canQueue = false
  }
}function throttle(func, wait) {
  let last = 0;
  return function (...rest) {
    let now = +new Date();
    if (now - last > wait) {
      last = +new Date()
      func.apply(this, rest)
    }
  }
}指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
window.addEventListener('scroll',function(){
    if(this.timer){
        clearTimeout(this.timer);
    }
    this.timer = setTimeout(function(){
        console.log('我正在执行');
    },1000)
})    function debounce(func, wait) {
      let timer;
      return function (...rest) {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          func.apply(this, rest)
        }, wait)
      }
    }
标签:按钮 执行 场景 net 搜索 app block als 大小
原文地址:https://www.cnblogs.com/shenggao/p/12329394.html