美文网首页
js节流和防抖

js节流和防抖

作者: Victor_818 | 来源:发表于2019-03-07 15:57 被阅读0次

节流:每隔一段时间触发一次

<input type="text" id="input" />
// 方法一:
function throttle(fn,delay){
    let valid = true
    return function() {
       if(!valid){
           return false 
       }
        valid = false
        setTimeout(() => {
            fn()
            valid = true;
        }, delay)
    }
}
// 方法二:
 function throttle(fn, wait) {
      let time = null;
      return function() {
          if (!time) {
              time = setTimeout(() => {
                  time = null;
                  fn();
              }, wait);
          }
      };
  }
// 一直输入,每隔两秒触发一次fn
let oInput = document.getElementById("input");
oInput.oninput = throttle(fn, 2000);

防抖:在一段时间里,只触发一次。

<input type="text" id="input" />
// 方法一:
function debounce(fn,delay){
    let timer = null //借助闭包
    return function() {
        if(timer){
            clearTimeout(timer) 
            timer = setTimeOut(fn,delay) 
        }else{
            timer = setTimeOut(fn,delay) 
        }
    }
}
// 方法二:
function debounce(fn,delay){
    let timer = null //借助闭包
    return function() {
        if(timer){
            clearTimeout(timer) 
        }
        timer = setTimeout(fn,delay) // 简化写法
    }
}
// 一直输入,不会触发fn,只有停止输入2秒后,才会触发一次fn
let oInput = document.getElementById("input");
oInput.oninput = throttle(fn, 2000);

相关文章

网友评论

      本文标题:js节流和防抖

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