js手写——防抖

js手写打卡Day01

js 复制代码
// 事件触发后等待n秒才执行,期间如果重新触发就重新计时
// 每次触发清除一个定时器,再设置定时器

// 尾执行
const debounce = (fn,delay) => {
  let timer = null;
  return function(...args) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this,args);
      },delay)
  }
}

/* const log = debounce(()=> console.log('hello world'),1000);
log();
log();
log();
 */
// 立即执行
// 在尾执行的基础上加一个首执行
const debounce2 = (fn, delay, immediate) => {
  let timer = null;
  if (immediate === false) {
    return function (...args) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, args);
      }, delay);
    }
  } else {
    return function (...args) {
      if (!timer) {
        fn.apply(this, args);
      }
      clearTimeout(timer);
      timer = setTimeout(() => {
        timer = null;
      }, delay);
    }
  }
}

const log = debounce2(()=> console.log('hello world'),1000,false);
log();
log();
log();
相关推荐
小林攻城狮4 小时前
使用 Transport 节流解决 Vercel AI SDK 流式渲染卡死问题
前端·react.js
前端缘梦4 小时前
告别 TS 运行时类型漏洞!Zod 完整入门实战教程(前端 / 全栈必备)
前端·react.js·全栈
the_answer5 小时前
Webpack vs Vite 深度对比分析
前端·webpack
转转技术团队5 小时前
验证码识别实战:前端不写页面,改训模型了?
前端
MomentYY5 小时前
Temperature:AI 的“脑洞旋钮”
前端·llm·ai编程
远航_5 小时前
OpenSpec 完整详细介绍
前端·后端
召钱熏6 小时前
状态枚举正确≠渲染正确:一个语音按钮的状态机边界修复实录
android·前端
SkyWalking中文站6 小时前
认识 Horizon UI · 1/17:SkyWalking 新一代可观测性控制台
运维·前端·监控
cidy_986 小时前
Dify 操作教程:工作流编排 & Chat 对话编排
前端·工作流引擎
tangdou3690986556 小时前
AI真好玩系列-2分钟快速了解DeepAgents | Quick Guide to DeepAgents in 2 Minutes
前端·javascript·后端