饥人谷技术博客

函数防抖(debounce)与函数节流(throttle)

2019-05-05  本文已影响4人  饥人谷_黄洪涛

函数防抖(debounce)

let timerId;
function debounce(fn, delay){
  clearTimeout(timerId);
  timerId = setTimeout(fn, delay);
}

const inputa = document.getElementById('inputa');
inputa.addEventListener('keyup', (e) => {
  debounce((value = e.target.value) => console.log(value), 2000);
});

函数节流(throttle)

let timerIdTh;
function throttle(fn, delay){
  if(timerIdTh){
    console.log('技能冷却中。。。');
    return;
  }
  timerIdTh = setTimeout(() => {
    clearTimeout(timerIdTh);
    timerIdTh = '';
    fn();
  }, delay);
}

const buttona = document.getElementById('buttona');
buttona.addEventListener('click', (e) => {
  throttle(() => console.log('哦里呀给'), 2000);
});

本文标题:函数防抖(debounce)与函数节流(throttle)
文章作者:黄洪涛
发布时间:2019年05月05日 - 23:05
最后更新:2019年05月05日 - 16:05
原始链接:https://hongtao-huang.github.io/函数防抖与函数节流/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

上一篇 下一篇

猜你喜欢

热点阅读