人间熙攘,好久不见

vuePress-theme-reco Magic    2017 - 2023
人间熙攘,好久不见 人间熙攘,好久不见

Choose mode

  • dark
  • auto
  • light
Home
Category
  • tools
  • Zsh
  • iTerm2
  • Front-end
  • 版本控制-Git
  • Rust
  • skia-safe
  • 第三方对接
  • MQTT
  • Powershell
  • python
  • MD5
  • SHA1
  • wsl2
Tags
TimeLine
GitHub
  • Github (opens new window)
  • Before (opens new window)
author-avatar

Magic

23

文章

15

标签

Home
Category
  • tools
  • Zsh
  • iTerm2
  • Front-end
  • 版本控制-Git
  • Rust
  • skia-safe
  • 第三方对接
  • MQTT
  • Powershell
  • python
  • MD5
  • SHA1
  • wsl2
Tags
TimeLine
GitHub
  • Github (opens new window)
  • Before (opens new window)
  • FrontEnd

    • 使用 Vue + TypeScript 开发 Chrome Extensions 🐱‍👤
    • Debounce Throttling ~
    • 从 Echarts 看 Zrender 的使用
    • Performance Yes 🎉
    • Rollup + Typescript => NPM Package
    • Svelte 事件问题

Debounce Throttling ~

vuePress-theme-reco Magic    2017 - 2023

Debounce Throttling ~

Magic 2021-03-01 Front-end

防抖和节流的简单实现

# Debounce

  • 防抖:延迟一段时间执行,间隔某端时间没人上车后发车
function debounce(callback, timeout, immediate) {
  let timer = null;
  return function() {
    let args = arguments; // 保存参数
    const later = () => {
      timer = null;
      !immediate && callback.apply(this, args); // 尾部调用
    };
    const callNow = immediate && !timer; // 是否 首次调用,首部调用
    clearTimeout(timer);
    timer = setTimeout(later, timeout); // 重启一个定时器调用
    callNow && callback.apply(this, args); // 立即调用
  }
}

# Throttling

  • 节流:滚动发车
// 版本一:记录时间
function throttling(callback, waitTime) {
  let currentTime = 0;
  return function() {
    if (currentTime === 0 || Date.now() - currentTime > waitTime) {
      currentTime = Date.now();
      callback.apply(this, arguments);
    }
  }
}
// 版本二:使用间隔时间反转记录
fucniton throttling(callback, waitTime) {
  let disable = false;
  return function() {
    if (!disable) {
      disable = true;
      callback.apply(this, arguments);
      setTimeout(() => disable = false, waitTime); // 使用延迟时间来做更新判断
    }
  }
}
欢迎来到 人间熙攘,好久不见
看板娘