惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Check Point Blog
J
Java Code Geeks
腾讯CDC
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
罗磊的独立博客
Last Week in AI
Last Week in AI
B
Blog
IT之家
IT之家
S
SegmentFault 最新的问题
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
博客园 - 聂微东
U
Unit 42
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
MyScale Blog
MyScale Blog

博客园 - howhy

TypeScript any vs unknown 详细对比 TypeScript interface vs type 完整对比 html 元素包含关系 this 指向 空对象 Object.keys for ...in Reflect.ownKeys ...区别 逻辑运算符和空值运算符 运算符优先级 js 类型显式转换 js 高级函数 js 方法重载 fetch timeout js 任务顺序执行 暂停 js 并发任务 判断两个对象是否相同 js 动态拦截属性 js 通用动画 js groupby 实现 instanceof 操作符 js 单例模式 js 数组去重和扁平方法 js 继承方法 js new的过程实现 js deepCopy js '=='的隐性类型转换规则
js 防抖和节流
howhy · 2025-12-29 · via 博客园 - howhy
// 实现防抖函数
function debounce(fn, delay, immediate = false) {
    // 实现
    let timer=null;
    let result=null;
    return function(...args){
        if(timer){
            clearTimeout(timer);
            timer=null;
        }
        if(immediate){
            const callnow=!timer;
            timer=setTimeout(()=>{
                timer=null;
            },delay);
            if(callnow){
                result=fn.apply(this,args);
            }
        }else{
            timer=setTimeout(()=>{
                result=fn.apply(this,args);
            },delay)
        }
        return result;
    }
}
function throttle(fn, limit) {
    let timer = null;
    let lastTime = 0;
    
    return function(...args) {
        const now = Date.now();
        const remaining = limit - (now - lastTime);
        
        // 清除之前的定时器
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        
        // 应该立即执行
        if (remaining <= 0) {
            fn.apply(this, args);
            lastTime = now;
        } 
        // 设置定时器延迟执行
        else {
            timer = setTimeout(() => {
                fn.apply(this, args);
                lastTime = Date.now();
                timer = null;
            }, remaining);
        }
    };
}