ZiMingの宝藏之地
首页项目归档笔记照片墙音乐灵境说说杂谈友链关于
知识库
138 篇文档 / 65 个目录
目录菜单
主页知识库
飞书飞书知识库/前端/面试/JS/js 基础/防抖 节流

防抖 节流

同步时间:2026-05-28T14:46:00

https://flowus.cn/375ce54a-3804-4d56-8580-f1abf9afde14

思维导图

图片

图片

代码

//防抖函数
//_this 是 接收原函数this
//...args 是 剩余参数
//核心功能:开启定时器记录id,在代码前面清除定时器
export function debounce(fn, delay = 0) {
  let timeId = null
  return function (...args) {
    let _this = this
    if (timeId) clearTimeout(timeId)
    timeId = setTimeout(function () {
      fn.apply(_this, args)
    }, delay)
  }
}
//节流函数
export function throttle(fn, delay = 0) {
  let timeId = null
  return function (...args) {
    let _this = this
    //如果不存在定时器
    if (!timeId) {
      timeId = setTimeout(function () {
        fn.apply(_this, args)
        timeId = null
      }, delay)
    }
  }
}

export function throttle(fn, delay = 0) {
  let timeId = null
  return function (...args) {
    let _this = this
    //如果不存在定时器
    if (timeId) return;

      timeId = setTimeout(function () {
        fn.apply(_this, args)
        timeId = null
      }, delay)
    }

}

Table of Contents