防抖和节流

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内的函数将不会被调用。

防抖的适用场景

  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.

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享