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();
相关推荐
DEMO派2 小时前
JavaScript数据存储三剑客:Object、Map与WeakMap完全指南
开发语言·前端·javascript
一拳不是超人2 小时前
半年AI编程实战总结:从工具到心法,让AI成为你的超能力
前端·人工智能·ai编程
阿杜杜不是阿木木2 小时前
从0到1构建像Claude Code那样的Agent(二):工具
前端·chrome·agent·ai编程·cluade code
cramer_50h2 小时前
Python的web开发框架Django再次更新
前端·python·django
weixin_6682 小时前
Clawith 大模型设计逻辑与前端接口架构分析 -AI分析
前端·人工智能·架构
x-cmd2 小时前
[x-cmd] Chrome DevTools MCP 更新:支持 coding agent 直接接管当前的浏览器窗口
前端·chrome·ai·agent·chrome devtools·x-cmd·mcp
芭拉拉小魔仙2 小时前
Vue v-html 中事件绑定失效问题及解决方案
javascript·vue.js·html
Never_Satisfied2 小时前
在HTML & CSS中,user-select属性详解
前端·css·html
_果果然2 小时前
除了防抖和节流,还有哪些 JS 性能优化手段?
javascript·vue.js·性能优化