• 主页
  • 个人简介
    • 圣墨 photo

      圣墨

      一个爱折腾,有诗有远方的人

    • Learn More
    • Github
    • Cnblogs
    • Weibo
  • 文章
    • 所有文章
    • 所有标签
  • Html&Css
  • Javascript
  • 设计模式
  • 前端性能优化
  • 原生实现专题
  • 数据结构与算法
  • Book
  • 面试题
  • 前端工具
  • 随记

手动实现防抖

16 Oct 2019

Reading time ~1 minute

手动实现防抖

含义

  • 防抖:不管事件触发频率多高,一定是在时间触发n秒后才执行,如果你在事件触发n秒内又触发,就以新的事件的时间为准,重新计时。

实现

  • 简单实现防抖
function debounce(fn, wait) {
    // 缓存定时器
    let timer = null;
    return function(...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, wait)
    }
}

// 处理函数
function handle() {    
	console.log('测试防抖'); 
}

// 滚动事件
window.addEventListener('scroll', debounce(handle, 1000));
  • 需要立即执行的防抖
function debounce(fn, wait, immediate = true) {
    // 缓存定时器
    let timer = null;
    return function(...args) {
        clearTimeout(timer);
        if(immediate && !timer) {
            fn.apply(this, args)
        }
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, wait)
    }
}

参考学习:

https://github.com/ConardLi/awesome-coding-js/blob/master/JavaScript/%E9%98%B2%E6%8A%96.md



javascript  微博  QQ  朋友圈