• 节流-throttle
  • 防抖-debounce

    节流

    节流理解起来就是技能冷却中,比如我们打王者的时候,「闪现」是120s一次,当你用过「闪现」这个技能的时候,120s之内你是不能再次使用「闪现」的。
    1. // 节流就是「技能冷却中」
    2. const throttle = (fn, time) => {
    3. let 冷却中 = false
    4. return (...args) => {
    5. if(冷却中) return
    6. fn.call(undefined, ...args)
    7. 冷却中 = true
    8. setTimeout(()=>{
    9. 冷却中 = false
    10. }, time)
    11. }
    12. }
    1. const throttle = (f, time) => {
    2. // 定义定时器
    3. let timer = null
    4. return (...args) => {
    5. if(timer) {return}
    6. f.call(undefined, ...args)
    7. timer = setTimeout(()=>{
    8. timer = null
    9. }, time)
    10. }
    11. }
    使用方法: ```javascript const f = throttle(()=>{console.log(‘hi’)}, 3000)

f() // 打印 hi f() // 技能冷却中

  1. <a name="cJAjV"></a>
  2. ### 防抖
  3. 防抖就是「回城被打断」
  4. ```javascript
  5. const debounce = (fn, time) => {
  6. let 回城计时器 = null
  7. return (...args)=>{
  8. if(回城计时器 !== null) {
  9. clearTimeout(回城计时器) // 打断回城
  10. }
  11. // 重新回城
  12. 回城计时器 = setTimeout(()=>{
  13. fn.call(undefined, ...args) // 回城后调用 fn
  14. 回城计时器 = null
  15. }, time)
  16. }
  17. }