美文网首页
函数的节流和防抖

函数的节流和防抖

作者: chasing_dream | 来源:发表于2021-11-24 14:25 被阅读0次
<input type="text" id="inp">
<script>
var oInp = document.getElementById('inp');
// var timer = null;
// function ajax(e) {
//  console.log(e, this.value)
// }

// oInp.oninput = function(e) {
//  var _self = this, _arg = arguments;
//  clearTimeout(timer);
//  timer = setTimeout(function() {
//      ajax.apply(_self, _arg);
//  }, 1000)
// }
function debounce(handler, delay) {
    var timer = null;
    return function(e) {
        console.log(e)
        var _self = this, _arg = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            handler.apply(_self, _arg);
        }, delay)
    }

}
function ajax(e) {
    console.log(e, this.value);
}
oInp.oninput = debounce(ajax, 2000)
</script>

节流:

    //函数节流
// var oDiv =document.getElementById('show');
// var oBtn =document.getElementById('btn');

// function throttle(handler, wait) {
//  var lastTime = 0;
//  return function(e) {
//      var nowTime = new Date().getTime();
//      if(nowTime - lastTime > wait) {
//          // handler();
//          handler.apply(this, arguments)
//          lastTime = nowTime;
//      }
//  }
// }
// function buy(e) {
//  console.log(this,e)
//  oDiv.innerText = parseInt(oDiv.innerText) + 1;
// }
// oBtn.onclick = throttle(buy, 1000)

相关文章

网友评论

      本文标题:函数的节流和防抖

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