aaa.防抖和节流

1. 防抖

防抖是多次执行变为最后一次执行

function debounce() {
  timer = null;
  return function () {
      if (timer) {
          clearTimeout(timer);
          timer = null;
      }
      timer = setTimeout(function () {
        console.log('boom')
      }, 2000)
  }
}
var run = setInterval(debounce(),1000)    //只执行最后一次
setTimeout(()=>{
  clearInterval(run)
},5000)

这种事简略写法,节流某函数写法如下

function debounce(fn, wait) {
  timer = null;
  return function () {
      var context = this
      var args = arguments
      if (timer) {
          clearTimeout(timer);
          timer = null;
      }
      timer = setTimeout(function () {
          fn.apply(context, args)   //节流fn函数
      }, wait)
  }
}
var fn = function () {
  console.log('boom')   //do something
}
var run = setInterval(debounce(fn,2000),1000)
setTimeout(() =>{
  clearInterval(run)
},5000)

2. 节流

节流是多次执行变成每隔一段时间执行一次

function throttle(fn, gapTime) {
  let _lastTime = null;
  return function () {
    let _nowTime = + new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn();
      _lastTime = _nowTime
    }
  }
}
let fn = ()=>{
  console.log('boom')
}
var run = setInterval(throttle(fn,2000),10)
setTimeout(() => {
  clearInterval(run)
}, 10000);

fn函数实现节流,本来10ms触发一次变成2000ms触发一次

ps:防抖是多次执行变为最后一次执行,节流是多次执行变成每隔一段时间执行一次,节流会稀释执行频率

你可能感兴趣的:(aaa.防抖和节流)