函数的节流和防抖

<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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容