防抖的封装

156 阅读1分钟

防抖

事件影响函数在一段事件后在执行

应用场景

  1. 搜索框输入
  2. scroll 事件滚动触发
  3. 表单验证
  4. 按钮提交
  5. 浏览器缩放事件,resize事件。
const btn = document.querySelector("#btn");

function debounce(func, time, immediate) {
  let timeout,
    result = null;
  let debounced = function () {
    let _this = this;
    let ars = arguments;
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      timeout = setTimeout(() => {
        result = func.apply(_this, ars);
        timeout = null;
      }, time);
    } else {
      timeout = setTimeout(function () {
        func.apply(_this, ars);
      }, time);
    }
    return result;
  };
  debounced.cancel = function () {
    clearTimeout(timeout);
    timeout = null;
  };
  return debounced;
}

let count = 0;
let doSome = debounce(fn, 3000);
btn1.onclick = () => {
  doSome.cancel();
};
function fn(e) {
  console.log(e);
  console.log(this);
  btn.textContent = count++;
}
btn.onmousemove = doSome;