防抖、节流、定时器

104 阅读1分钟

github.com/Advanced-Fr…

防抖触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
节流高频事件触发,但在n秒内只会执行一次***节流会稀释函数的执行频率

防抖

function debounce(fn, time) {
  let timeout = null; // 创建一个标记用来存放定时器的返回值
  console.log("1", this); //指向window
  return function () {
    console.log("2", this); //this指向的是出发该动作的节点
    clearTimeout(timeout); // 每当用户输入的时候把前一个 setTimeout clear 掉
    timeout = setTimeout(() => {
      // 然后又创建一个新的 setTimeout,  这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
      fn.apply(this, arguments); //将节点的this绑定到sayHi函数里边去,以防fn函数要用到this
    }, time);
  };
}

// 测试
function task() {
  console.log("run task");
}
const debounceTask = debounce(task, 1000);
window.addEventListener("scroll", debounceTask);

节流

// 节流
function throttle(fn, time) {
  let canRun = true; // 通过闭包保存一个标记
  return function () {
    if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
    canRun = false; // 立即设置为false,当定时器没有执行的时候标记永远是false,在开头被return掉
    setTimeout(() => {
      // 将外部传入的函数的执行放在setTimeout中
      fn.apply(this, arguments);
      canRun = true; // 最后在setTimeout执行完毕后再把标记设置为true(关键 )
    }, time);
  };
}

// 测试
function task() {
  console.log("run task");
}
const throttleTask = throttle(task, 1000);
window.addEventListener("scroll", throttleTask);

定时器实战

function getCaptcha() {
  const _this = this;
  this.realGetCaptcha();
  clearInterval(this.timeout); //timeout要定义成全局的,不能在getCaptcha函数内定义,会出问题
  this.timeout = setInterval(_this.realGetCaptcha, 300000); //发送图形验证码的时间,5分钟自动更新一次
}
function realGetCaptcha() {}