节流

需求

节流的原理很简单:

如果你持续触发事件,每隔一段时间,只执行一次事件。

根据首次是否执行以及结束后是否执行,效果有所不同,实现的方式也有所不同。

我们用 leading 代表首次是否执行,trailing 代表结束后是否再执行一次。

关于节流的实现,有两种主流的实现方式,一种是使用时间戳,一种是设置定时器。

节流 在 CodePen 中打开

// 节流
function throttle(func, delay = 50){
  let lastTime = 0;

  return function(...arg){
    let now = +new Date();
    let self = this;
    if( now-lastTime > delay){
      func.apply(self, arg)
      lastTime = now;
    }
  }
}

function sayHello(){
  console.log('hello')
}

let throttleButton = document.getElementById('throttle');
throttleButton.onclick = throttle(sayHello, 1000);

参考

https://github.com/mqyqingfeng/Blog/issues/26

results matching ""

    No results matching ""