一、节流:窗口调整(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