平时debounce(防抖)用得多,throttle用得少,记下写 throttle 时遇到的低级错误。
 节流,一定时间内多次操作,在最早操作的若干延迟后执行。
 场景参考:周期上报,有的数据不急着报,只要定时上报即可,开发者可能在多个地方调用周期上报,只需把数据存起来一起报即可。
防抖,一定时间内多次操作,在最后一次操作的若干延迟后执行。
 场景参考:搜索框输入后立即进行搜索,当用户输入不改变 500毫秒后才向服务器发请求。
一开始写的节流函数是这样的
// 节流
function throttle(func, delay) {
  let throttleTimer = null
  return function() {
    let _this = this
    let _args = arguments
    if(!throttleTimer) {
      throttleTimer = setTimeout(()=>{
        func.apply(_this, _args)
        throttleTimer = null
      }, delay)
    }
    return throttleTimer
  }
}
这里假设滚动屏幕后要上报一下
const t = throttle((a)=>{
  console.log(a)
}, 1000)
let timer = null
window.onscroll = ()=>{
  const m = Math.random()
  console.log('随机值:', m)
  timer = t(m)
}
可以发现实际用了第一个参数
 好像不符合预期? 怎么不是用最后一个的参数?
 直觉上不对,加日志看看
// 节流
function throttle(func, delay) {
  let throttleTimer = null
  return function() {
    let _this = this
    let _args = arguments
    console.debug('预期_args更新了', _args)
    if(!throttleTimer) {
      throttleTimer = setTimeout(()=>{
        func.apply(_this, _args)
        throttleTimer = null
      }, delay)
    }
    return throttleTimer
  }
}

 可以看到_args确实有更新的,但 setTimeout 里打出来的仍是第一次的_args的值。
 再看看,原来是_args重新定义了。
 如果把_args挪到前面,行成闭包,就符合预期了。
// 节流
function throttle(func, delay) {
  let throttleTimer = null
  let _args // 把 args 定义放这,形成闭包
  return function() {
    let _this = this
    _args = arguments
    if(!throttleTimer) {
      throttleTimer = setTimeout(()=>{
        func.apply(_this, _args)
        throttleTimer = null
      }, delay)
    }
    return throttleTimer
  }
}

 这里是变量作用域导致的,一开始_args的作用域在 throttle 返回的函数里,当调用了一次函数 t,setTimeout 里存着_args的值。
 
 下次调用函数 t,_args重新定义,就是新的内存地址了,再去改变他的值并不改变之前 setTimeout 传入参数的值。
 而把_args作用域提升到 throttle 里,就形成了闭包,我们代码对 t 有引用,_args跟throttleTimer就一直在。
 

 setTimeout 的_args就一直用的同一份,之后多次调用函数 t,更新_args的值就生效了。


















![[游戏开发][虚幻5]新建项目注意事项](https://img-blog.csdnimg.cn/direct/13ca23567b4844888aa638725ed63840.png)
