节流和防抖

本文介绍了Web开发中常用的节流和防抖技术,它们用于控制函数执行频率,尤其在处理窗口调整、滚动和键盘输入等事件时,以提高性能并合理利用资源。作者提供了loadsh库的实现示例来详细讲解这两种技术的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Web开发和编程中,“节流”和“防抖”是两种用于控制函数执行频率的技术。这些技术特别适用于那些不应该频繁运行的代码场景,如在窗口调整大小、滚动或键盘输入时,以优化性能和资源利用。

节流

节流是一种确保函数每隔指定的毫秒数最多执行一次的技术。这意味着无论函数被触发多少次,它都只按固定频率执行,例如每200毫秒执行一次。这种方法适用于你想要限制的功能,如处理滚动事件或窗口大小调整,你希望在保持性能的同时,还能足够频繁地捕捉和处理事件。

来看一下loadsh 的实现,参数为:需要执行的类,多久执行一次,在开始时执行,还是结束时执行。

function throttle(func, wait, options) {
    let leading = true;
    let trailing = true;

    if (typeof func !== 'function') {
        throw new TypeError('Expected a function');
    }
    if (isObject(options)) {
        leading = 'leading' in options ? !!options.leading : leading;
        trailing = 'trailing' in options ? !!options.trailing : trailing;
    }
    return debounce(func, wait, {
        leading,
        trailing,
        maxWait: wait,
    });
}

防抖 (Debouncing)

防抖确保一个函数只在上次被调用后的一定空闲时间过去之后才执行。这种技术适用于当你想确保在某个动作完成后只触发一次函数的场景。例如,当用户在搜索字段中完成输入时,你可能使用防抖,在他们停止输入后再执行搜索。

来看一下loadsh 的实现,代码比较长,只留下了一些重要的方法,debounce 返回的是闭包,多次调用时用的还是同一套外层函数定义的数据。setTimeout 到期时检查是否需要调用函数,关键是shouldInvoke方法,判断是否需要调用。

import isObject from './isObject.js';
import root from './.internal/root.js';

/**
 
function debounce(func, wait, options) {
    let lastArgs;
    let lastThis;
    let maxWait;
    let result;
    let timerId;
    let lastCallTime;
    let lastInvokeTime = 0;
    let leading = false;
    let maxing = false;
    let trailing = true;

    function invokeFunc(time) {
        const args = lastArgs;
        const thisArg = lastThis;

        lastArgs = lastThis = undefined;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
    }

    function startTimer(pendingFunc, milliseconds) {
        if (useRAF) {
            root.cancelAnimationFrame(timerId);
            return root.requestAnimationFrame(pendingFunc);
        }
        // eslint-disable-next-line @typescript-eslint/no-implied-eval
        return setTimeout(pendingFunc, milliseconds);
    }

    function leadingEdge(time) {
        // Reset any `maxWait` timer.
        lastInvokeTime = time;
        // Start the timer for the trailing edge.
        timerId = startTimer(timerExpired, wait);
        // Invoke the leading edge.
        return leading ? invokeFunc(time) : result;
    }

    function remainingWait(time) {
        const timeSinceLastCall = time - lastCallTime;
        const timeSinceLastInvoke = time - lastInvokeTime;
        const timeWaiting = wait - timeSinceLastCall;

        return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
    }

    function shouldInvoke(time) {
        const timeSinceLastCall = time - lastCallTime;
        const timeSinceLastInvoke = time - lastInvokeTime;

// 第一次调用,活动已经停止,默认为已到期,系统时间出现负值,正常情况不会,这里也将其视为
// 已结束,或者我们已达到 `maxWait` 限制。

        return (
            lastCallTime === undefined ||
            timeSinceLastCall >= wait ||
            timeSinceLastCall < 0 ||
            (maxing && timeSinceLastInvoke >= maxWait)
        );
    }

    function timerExpired() {
        const time = Date.now();
        if (shouldInvoke(time)) {
            return trailingEdge(time);
        }
        // Restart the timer.
        timerId = startTimer(timerExpired, remainingWait(time));
        return undefined;
    }

    function trailingEdge(time) {
        timerId = undefined;

        // Only invoke if we have `lastArgs` which means `func` has been
        // debounced at least once.
        if (trailing && lastArgs) {
            return invokeFunc(time);
        }
        lastArgs = lastThis = undefined;
        return result;
    }

    function debounced(...args) {
        const time = Date.now();
        const isInvoking = shouldInvoke(time);

        lastArgs = args;
        lastThis = this;
        lastCallTime = time;

        if (isInvoking) {
            if (timerId === undefined) {
                return leadingEdge(lastCallTime);
            }
            if (maxing) {
                // Handle invocations in a tight loop.
                timerId = startTimer(timerExpired, wait);
                return invokeFunc(lastCallTime);
            }
        }
        if (timerId === undefined) {
            timerId = startTimer(timerExpired, wait);
        }
        return result;
    }
    return debounced;
}

export default debounce;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值