关于节流函数

2020 年 11 月 4 日
 rodrick

之前学的时候自己是这样写的

function throttle(fn, wait) {
      let lastTime = 0
      let timer = null
      let nowTime = new Date().getTime();

      return function (...args) {
        if (nowTime - lastTime > wait) {
          fn.apply(this, args)
          lastTime = nowTime
        } else if (timer === null) {
          timer = setTimeout(() => {
            timer = null
            fn.apply(this, args)
          }, wait)
        }
      }
    }

使用的时候发现如果定时器结束执行 fn.apply(this, args) 的话,那么这个 args 是当前时间减去 wait 的那个时间点的参数,并不是当前时间的参数
在一些监控滑动位置等情况时[args 是当前位置信息]可能会导致执行 fn 的时候并不是使用的最准确的位置信息,那么怎么能拿到准确时间点的参数呢

2262 次点击
所在节点    JavaScript
6 条回复
IsaacYoung
2020 年 11 月 4 日
你可能需要防抖
shabbyin
2020 年 11 月 4 日
同楼上看法
监控滑动位置为什么要用节流
在滑动结束的时候提交一下位置数据不就可以了吗
rodrick
2020 年 11 月 4 日
@gyjames95
@IsaacYoung
是滑动的过程中去间隔性触发事件,不是滑动结束,这个只是举个例子,主要是这个参数不是准确时间点的参数的问题
akaxiaok339
2020 年 11 月 4 日
``` js
function throttle(fn, wait) {
let lastTime = 0
let timer = null
let nowTime = new Date().getTime();
let params = null
return function (...args) {
params = args;
if (nowTime - lastTime > wait) {
fn.apply(this, args)
lastTime = nowTime
} else if (timer === null) {
timer = setTimeout(() => {
timer = null
fn.apply(this, params)
}, wait)
}
}
}
```
rodrick
2020 年 11 月 4 日
@akaxiaok339 害...这么简单我居然没想到
hurrytospring
2020 年 11 月 4 日
tail leading 的概念?,看看 lodash 里面

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.ih06.com/t/721663

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX