节流、防抖

69 阅读1分钟
  • 节流,多次触发时,只会在一定时间内执行一次。触发事件执行任务设置时间间隔,在间隔内若再次触发事件不会执行任务,在时间间隔外若再次触发则执行任务重新设置时间间隔。
//写法一
function throttle(func, delay) {
    let timer
    return function() {
        if(timer) return
        let context = this
        let args = arguments
        timer = setTimeout(() => {
            func().apply(context, args)
            timer = null
        }, dalay)
    }
}
//写法二
function throttle(func, delay) {
    let pre = 0
    return function() {
        let now = new Date()
        let context = this
        let args = arguments
        if(now-pre > delay) {
            func.apply(context, args)
            pre = now
        }
    }
}
  • 防抖,在第一次触发事件时,不立即执行函数而是给出一个期限值,在此期限值内没有再次触发事件那么就触发函数,如果有再次触发事件那么重新开始计数。
function debounce(func, delay) {
    let timer
    return function () {
       let context = this
       let args = arguments
       clearTimeout(timer)
       timer = setTimeout(() => {
            func().apply(context,args)
        }, delay)
    }
}
  • 两者区别:节流不管触发的多频繁都会保证在一定时间内执行一次;防抖只会在最后一次触发结束后一定时间内执行一次。
  • 两者都使用到了闭包。