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

      圣墨

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

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

手动实现节流

16 Oct 2019

Reading time ~1 minute

手动实现节流

含义

  • 节流: 在某段时间内,不管你触发了多少次回调,我都只认第一次,并在计时结束时给予响应。

实现

function throttle(fn, time) {
    let pre = 0;
    let timer = null;
    return function(...args) {
        if(Date.now() - pre > time) {
            clearTimeout(timer);
            timer = null;
            pre = Date.now();
            fn.apply(this, args);
        } else if(!timer) {
            timer = setTimeout(() => {
                fn.apply(this, args);
            })
        }
    }
}

参考学习:

https://github.com/ConardLi/awesome-coding-js/blob/master/JavaScript/%E8%8A%82%E6%B5%81.md



javascript  微博  QQ  朋友圈