防抖和节流

136 阅读1分钟

1.防抖

防抖的实现

function debounce (fn, delay) {
    return function (args) {
        let that = this
        let _args = args
        clearTimeout(fn.id)
        fn.id = setTimeout(function() {
            fn.call(that, _args)
        }
    }
}

// 项目中使用
let debounceAjax = debounce(ajax, 500)
debounceAjax(arguments_1)

防抖的原理
当上一次触发事件和下一次触发事件的时间差 < delay 时,debounce函数 会重置倒计时的时间,只要保持在delay时间内触发事件,debounce内的函数将不会被调用。 防抖是维护一个计时器,规定在delay时间后触发函数,但是在delay时间内再次触发的话,都会清除当前的 timer 然后重新设置超时调用,即重新计时。这样一来,只有最后一次操作能被触发。

防抖的适用场景

  1. 监听input框的输入值变化,输入结束后提交处理
  2. 表单的提交按钮触发事件

2.节流

** 节流的实现 **

function throttle (fun, delay) {
    let last, deferTimer
    return function (args) {
        let that = this
        let _args = arguments
        let now = +new Date()
        if (last && now < last + delay) {
            clearTimeout(deferTimer)
            deferTimer = setTimeout(function () {
                last = now
                fun.apply(that, _args)
            }, delay)
        } else {
            last = now
            fun.apply(that, _args)
        }
    }
}

// 项目中使用
let throttleAjax = throttle(ajax, 500)
throttleAjax(arguments_1)

节流的原理
throttle函数在初始会立即执行一次throttle内的函数,然后fun每delay毫秒最多只调用一次。 节流是通过判断是否到达一定时间来触发函数,若没到规定时间则使用计时器延后,而下一次事件则会重新设定计时器。

节流的适用场景

  1. scroll滚动事件,监听当前页面滚动位置以执行相关操作