Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
TTFZippo opened this issue Jan 13, 2022 · 3 comments
Open

Comments

@TTFZippo
Copy link

// 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不就一样了吗?)

请教大佬解答

@yanpei2016
Copy link

yanpei2016 commented Jan 13, 2022 via email

@ANT-CYJ
Copy link

ANT-CYJ commented Jan 13, 2022 via email

@kingforever
Copy link

kingforever commented Jan 13, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants