/ JavaScript / 3663浏览

防抖(debounce)、节流(throttle)原理与实现

防抖(debounce)

防抖指在指定时间间隔内重复触发只保留这段时间内的最后一次触发,如果在指定时间内再次触发会重新开始计时。

function debounce (fn, interval) {
    var timer
    return function () {
        var that = this
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(function () {
            fn.apply(that, arguments)
        }, interval)
    }
}

节流(throttle)

节流指在指定时间间隔内只重复触发一次。

function throttle (fn, interval) {
    var timer, first = true
    return function () {
        var that = this
        if (first) {
            fn.apply(this, arguments)
            return first = false
        }
        if (timer) {
            return false
        }
        timer = setTimeout(function () {
            fn.apply(that, arguments)
            clearTimeout(timer)
            timer = null
        }, interval)
    }
}
更新于
JavaScript中的this到底指向谁?
JavaScript中的this到底指向谁?
手写一个Promise
手写一个Promise
手写一个call、apply、bind
手写一个call、apply、bind
JS如何等待多个异步操作完成后再进行操作
JS如何等待多个异步操作完成后再进行操作
原型
原型

0

  1. This post has no comment yet

发表回复