优化网络请求性能

本文介绍了前端开发中常见的性能优化方法,包括节流(throttle)、防抖(debounce)及函数记忆(memorize)等技术的应用实例。通过这些方法可以有效减少不必要的计算,提升用户体验。

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

一、节流:窗口调整(resize),页面滚动(scroll),频繁点击(click)

<div class="box">
    <div id="text">0</div>
    <button id="btn">点击</button>
</div>

 

var text=document.getElementById('text');
var btn=document.getElementById('btn');
//点击时,1s内只能触发一次,防止多次点击
btn.onclick= throttle(addFn,1000);
function addFn(e){
    console.log(this,e);//btn
    text.innerText=parseInt(text.innerText)+1;
}
// 节流 handler方法  waitTime 等待时间
function throttle(handler,waitTime){
    var lastTime=0;
    return function(e){
        var nowTime=new Date().getTime();
        if(nowTime-lastTime>waitTime){
            handler.apply(this,arguments);//改变this指向 window->btn
            lastTime=new Date().getTime();
        }
    }
}

 

 

二、防抖:实时搜索,拖拽

 <input type="text" name="" id="input"/> 
var input=document.getElementById('input');
//搜索时,延迟1s时间请求数据,防止频繁发送不必要的请求
input.oninput=debounce(ajaxFn,1000);
function ajaxFn(e){
    console.log(this.value,e);
}
// 防抖 handler方法  delayTime延迟时间
function debounce(handler,delayTime){
    var timer=null;
    return function(){
        var _arg=arguments;
        clearTimeout(timer);
        timer=setTimeout(function(){
            handler.apply(this,_arg);
        }.bind(this), delayTime);
    }

}

 三、函数记忆

// 函数角度优化函数记忆
function memorize(fn){
    var cache={};
    return function(){
        var key=arguments.length+ Array.prototype.join.call(arguments);//唯一key
        if(cache[key]){
            return cache[key];
        }else{
            cache[key]=fn.apply(this,arguments);
            return cache[key];
        }
    }
}
// 阶乘
function factorial(n){
    if(n==0||n==1){
        return 1;
    }else{
        return n*arguments.callee(n-1);
    }
}

var newFn=memorize(factorial);

console.time('2');
console.log(newFn(5))
console.timeEnd('2');// 2.18505859375ms

console.time('3');
console.log(newFn(5))
console.timeEnd('3');//0.1650390625ms

 

转载于:https://www.cnblogs.com/yuesu/p/9285063.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值