美文网首页饥人谷技术博客
函数防抖(debounce)与函数节流(throttle)

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

作者: 饥人谷_黄洪涛 | 来源:发表于2019-05-05 16:29 被阅读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 国际 转载请保留原文链接及作者。

相关文章

网友评论

    本文标题:函数防抖(debounce)与函数节流(throttle)

    本文链接:https://www.haomeiwen.com/subject/nkehoqtx.html