JS进阶-防抖与节流

263 阅读1分钟

1.防抖

在频繁操作时,操作完毕的指定时间后,被防抖函数被执行一次
如:需要在输入框输入完毕才发送请求获取搜索结果,对input事件函数加一层防抖,即可实现该功能

var debounce = function(fn = function() {}, delay = 0) {
    var args = [].slice.call(arguments, 2)
    var timer,
        _args,
        _this

    return function() {
        _this = this
        _args = [].slice.call(arguments)
        timer && clearTimeout(timer)
        timer = setTimeout(function() {
            fn.apply(_this, args.concat(_args))
        }, delay)
    }
}

2.节流

在频繁操作时,被节流函数在该操作期间每隔一个指定时间执行一次
如:点击按钮抽奖,设定节流时间为1s,频繁点击按钮的时间为4s,那么被节流函数每隔1s执行一次,即共执行4次

var throttle = function(fn = function() {}, delay = 0) {
    var args = [].slice.call(arguments, 2)
    var last = 0
    var now = 0
    var _args,
        _this

    return function() {
        now = Date.now()
        if (now - last < delay) {
            return
        }
        last = now
        _this = this
        _args = [].slice.call(arguments)
        fn.apply(_this, args.concat(_args))
    }
}

3.例子

  • html
<input type="text" id="ipt"/>
<button id="btn">点我</button>
  • js
function iptHandler(a, e) {
  console.log('ipt', a, e)
}

function btnHandler(a, e) {
  console.log('btn', a, e)
}

var debouncedIpt = debounce(iptHandler, 1000, 1)
var throttleBtn = throttle(btnHandler, 1000, 1)

ipt.oninput = debouncedIpt
btn.onclick = throttleBtn
  • 效果
    • 防抖效果
    • 节流效果