封装函数防抖

1.什么是函数防抖[debounce]?

函数防抖是优化高频率执行js代码的一种手段
可以让被调用的函数在一次连续的高频操作过程中只被调用一次

2.函数防抖作用

减少代码执行次数, 提升网页性能

3.函数防抖应用场景

oninput / onmousemove  / onscroll / onresize等事件
      function debounce(fn, delay) { //
        let timerId = null;
        return function () {
            let self = this;
            let args = arguments;
            timerId && clearTimeout(timerId);
            timerId = setTimeout(function () {
                fn.apply(self, args);
            }, delay || 1000);
        }
    }

      let oInput = document.querySelector("input");
      oInput.oninput = debounce(function (event) {
        console.log("发送网络请求");
        console.log(this);
        console.log(event);
    }, 5000);
posted @ 2020-12-23 11:56  砂糖一椰子  阅读(168)  评论(0编辑  收藏  举报