serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

可控制的节流 #6

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

题目 implement throttle() with leading & trailing option

接上一题。可由leading和trailing控制的节流方法。 leading为true,即每次wait时间过后的下一次循环执行func方法。 trailing为true, 每次wait时间过后直接执行func。 两者都为true,trailing优先。

例子


function a(b){
console.log(b)
}
var i=0;
let throttled=throttle(a,5000,optionsx);//x=1 || 2 ||  3 ||  4 
setInterval(() => {
throttled(i++);
}, 1000);

options1={leading:true,trailing:true}; // 0 5 10 options2={leading:true,trailing:false} //0 6 12 18 options3={leading:false,trailing:false} // options4={leading:false,trailing:true} //5 10 15

>答案

function throttle(func,wait,option = {leading: true,trailing: true}){ let flag=true; let preArgs=null; function setTime(){ //trailing为true,一直执行定时器 if(preArgs && option.trailing){ func.apply(this,preArgs); preArgs=null; setTimeout(setTime, wait); }else{ flag=true; } } return function(){ if(!flag){ preArgs=[...arguments]; }else{ if(option.leading){ func.apply(this,arguments); } flag=false; setTimeout(setTime,wait) } } }

//可以去掉flag,直接用定时器判断 function throttle(func,wait,option = {leading: true,trailing: true}){ let timer=null; let preArgs=null; function setTime(){ if(preArgs && option.trailing){ func.apply(this,preArgs); preArgs=null; setTimeout(setTime, wait); }else{ timer=null; } } return function(){ if(timer){ preArgs=[...arguments]; }else{ if(option.leading){ func.apply(this,arguments); } timer = setTimeout(setTime,wait) } } }