Skip to content

第7期 深入浅出throttle 的加强版throttle的wait参数问题 #51

Open
@TTFZippo

Description

@TTFZippo
// fn 是需要节流处理的函数
// wait 是时间间隔
function throttle(fn, wait) {
  
  // previous 是上一次执行 fn 的时间
  // timer 是定时器
  let previous = 0, timer = null
  ```javascript
  // 将 throttle 处理结果当作函数返回
  return function (...args) {
    
    // 获取当前时间,转换成时间戳,单位毫秒
    let now = +new Date()
    
    // ------ 新增部分 start ------ 
    // 判断上次触发的时间和本次触发的时间差是否小于时间间隔
    if (now - previous < wait) {
    	 // 如果小于,则为本次触发操作设立一个新的定时器
       // 定时器时间结束后执行函数 fn 
       if (timer) clearTimeout(timer)
       timer = setTimeout(() => {
          previous = now
        	fn.apply(this, args)
        }, wait)
    // ------ 新增部分 end ------ 
      
    } else {
       // 第一次执行
       // 或者时间间隔超出了设定的时间间隔,执行函数 fn
       previous = now
       fn.apply(this, args)
    }
  }
}

如果throttle 和 debounce都用同一个wait那就没有意义了吧?(和单纯throttle不就一样了吗?)

请教大佬解答

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions