js 节流和防抖

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

使用场景

  • 滚动加载更多

  • 鼠标移动事件

  • 按钮频繁点击

  • 游戏中的按键处理

function throttle(func, delay, options = {}) {
    let timeoutId = null;
    let lastTime = 0;
    const { leading = true, trailing = true } = options;
    
    return function(...args) {
        const context = this;
        const now = Date.now();
        
        // 第一次执行控制
        if (!lastTime && !leading) {
            lastTime = now;
        }
        
        const remaining = delay - (now - lastTime);
        
        if (remaining <= 0) {
            // 可以执行
            if (timeoutId) {
                clearTimeout(timeoutId);
                timeoutId = null;
            }
            lastTime = now;
            func.apply(context, args);
        } else if (trailing && !timeoutId) {
            // 设置延迟执行
            timeoutId = setTimeout(() => {
                lastTime = !leading ? 0 : Date.now();
                timeoutId = null;
                func.apply(context, args);
            }, remaining);
        }
    };
}

防抖是指触发事件后,在 n 秒后执行函数,如果在 n 秒内又触发了事件,则会重新计算执行时间。

使用场景

  • 搜索框输入建议

  • 表单验证

  • 窗口大小调整

  • 文本编辑器自动保存

function debounce(func, delay, immediate = false) {
    let timeoutId = null;
    
    return function(...args) {
        const context = this;
        
        // 清除之前的定时器
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        
        // 立即执行模式
        if (immediate && !timeoutId) {
            func.apply(context, args);
        }
        
        timeoutId = setTimeout(() => {
            // 非立即执行模式
            if (!immediate) {
                func.apply(context, args);
            }
            timeoutId = null;
        }, delay);
    };
}

 

posted @ 2025-11-25 11:35  howhy  阅读(5)  评论(0)    收藏  举报