饥人谷技术博客

函数防抖和函数节流

2020-03-11  本文已影响0人  kzc爱吃梨

防抖(debounce)


范例

let command
document.body.onscroll = () => {
    console.log('这里每次都执行')
    if(command)
        clearTimeout(command)
    command = setTimeout(() => {
        console.log('这里只执行很少次')
    }, 1000)
}

查看完整代码

封装

function debounce(fn, wait) {
    let timer = null
    return function() {
        if(timer) 
            clearTimeout(timer)
        timer = setTimeout(() => fn.apply(this, arguments), wait)
    }
}

let fn = () => console.log('这里只执行很少次')
fn = debounce(fn, 1000)

document.body.onscroll = fn

查看完整代码

节流(throttle)


范例


let gapTime = 1000 
let lastTime = null
let nowTime = null
let fn = () => console.log('我执行了')
document.body.onscroll = () => {
    nowTime = Date.now() 
    if(!lastTime || nowTime - lastTime > gapTime) {
        fn()
        lastTime = nowTime
    }

}

完整代码

封装

function throttle(fn, gapTime) {
    let lastTime = null
    let nowTime = null
    return function() {
        nowTime = Date.now()
        if(!lastTime || nowTime - lastTime > gapTime) {
            fn()
            lastTime = nowTime
        }
    }
}

let fn = () => console.log('我执行了')
fn = throttle(fn, 1000)

document.body.onscroll = fn

案例


用户在连续输入文字时如何实现自动保存,兼顾性能(保存频率不能太高)与可用性(边输入边保存)?

<!DOCTYPE html>
<html>
<head>
<meta name="description" content="节流自动保存文件案例" />
  <meta charset="utf-8">
  <title>节流自动保存文件案例</title>
</head>
<body>
  <textarea id="box" cols="50" rows="10"></textarea>
  <p>保存<span id="count">0</span>次</p>

  <script>
    const $ = s => document.querySelector(s)

    let count = 0
    save = throttle(save, 1000*3)
    $('#box').oninput = function() {
      save()
    }

    function save() {
      $('#count').innerText = ++count
    }

    function throttle(fn, gapTime) {
      let lastTime = null
      let nowTime = null
      return function() {
        nowTime = Date.now()
        if(!lastTime || nowTime - lastTime > gapTime) {
          fn()
          lastTime = nowTime
        }
      }
    }

    function debounce(fn, wait) {
      let timer = null
      return function() {
        if(timer) 
          clearTimeout(timer)
          timer = setTimeout(() => {
            fn.apply(this, arguments)
          }, wait)
      }
    }
  </script>
</body>
</html>

查看效果

上一篇下一篇

猜你喜欢

热点阅读