前端优化-防抖和节流

105 阅读1分钟

1、防抖

在第一次触发事件时,不立即执行函数,在事件被触发 n 秒后再执行回调,如果在这n秒内又被触发,则重新计时。

  • 非立即执行
function debounce(fn,wait=1000){
            let timer
            return function(){
             	let args=arguments
                let context=this
                if(timer){
                    clearTimeout(timer)
                }
                timer=setTimeout(function(){
                    fn.apply(context,args)
                },wait)
            }
}

  • 立即执行 触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。
function debounce(func,wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;
        if (timeout) clearTimeout(timeout);
        let callNow = !timeout;
        timeout = setTimeout(() => {
            timeout = null;
        }, wait)

        if (callNow) func.apply(context, args)
    }
}
  • 综合版本
/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
function debounce(func,wait,immediate) {
    let timeout;

    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            var callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
}

2、节流

指连续触发事件但是在 n 秒中只执行一次函数。

  • 定时器
function throttle(func,wait=1000){
    let timeout;
    return function () {
        let context = this;
        let args = arguments;
        if (timeout) return;
        timeout = setTimeout(() => {
            timeout = null;
            func.apply(context, args)
        }, wait)
    }
}
  • 时间戳
function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

参考:www.jianshu.com/p/c8b86b09d…