节流和防抖函数

本文详细介绍了JavaScript中节流(throttle)和防抖(debound)函数的实现原理及应用。节流函数用于限制函数调用频率,防抖函数则确保函数在一系列触发后仅执行一次,两者都是优化用户体验和提升性能的重要手段。

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


/**
 * 节流函数
 * @param {Funtion} method 回调函数
 * @param {Object} context 上下文地址
 * @param {number} delay 延迟时间ms
 */
function throttle(method, context, delay) {
    delay = delay || 500;
    var currentDate = new Date();
    method.startTime = method.startTime || 0;
    if (currentDate - method.startTime > delay) {
        method.call(context);
        method.startTime = new Date();
    }
    else {
        clearTimeout(method.timer);
        method.timer = setTimeout(function () {
            throttle(method, context, delay);
        }, 50);
    }
}


/**
 * 防抖函数
 * @param {Funtion} method 回调函数
 * @param {Object} context 上下文地址
 * @param {number} delay 延迟时间ms
 */
function debound(method, context, delay) {
    delay = delay || 200;
    clearTimeout(context.deboundId);
    context.deboundId = setTimeout(function () {
        method.call(context);
    }, delay);
}

转载于:https://www.cnblogs.com/jerrypig/p/10187368.html

如果你封装的节流防抖函数返回后面的函数没有执行,可能是因为在封装的过程中没有正确处理函数的执行逻辑。以下是一个修复的示例: ```typescript // utils/debounce.ts export function debounce(func: Function, delay: number) { let timer: NodeJS.Timeout | null = null; return function(...args: any[]) { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { func.apply(this, args); }, delay); }; } // utils/throttle.ts export function throttle(func: Function, delay: number) { let timer: NodeJS.Timeout | null = null; let lastRun = 0; return function(...args: any[]) { const currentTime = Date.now(); if (!timer) { func.apply(this, args); lastRun = currentTime; return; } if (currentTime - lastRun >= delay) { func.apply(this, args); lastRun = currentTime; } }; } ``` 在上面的示例中,修复了防抖函数节流函数的返回逻辑。 对于防抖函数,当延迟时间内再次触发时,会先清除之前的定时器,然后重新设置定时器。这样可以确保只有最后一次触发的定时器会执行回调函数。 对于节流函数,初始状态下,如果没有定时器存在,则立即执行回调函数。如果已经存在定时器,则根据当前时间与上次运行时间的差值判断是否达到节流时间间隔,如果满足条件,则执行回调函数。 请注意,以上示例是基于Node.js环境下的实现,如果你在浏览器环境中使用,请适当调整定时器的类型清除方式。另外,确保你正确使用这些封装的函数,并传递正确的参数回调函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值