serendipityApe / javascriptPromotion

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

节流 #5

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

题目 implement basic throttle()

实现节流,题目要求的节流和我们平常的不一样,上面题目要求节流的同时保持最大频率调用目标函数。

例子


let currentTime = 0

const run = (input) => { currentTime = 0 const calls = []

const func = (arg) => { calls.push(${arg}@${currentTime}) }

const throttled = throttle(func, 3) input.forEach((call) => { const [arg, time] = call.split('@') setTimeout(() => throttled(arg), time) }) return calls }

expect(run(['A@0', 'B@2', 'C@3'])).toEqual(['A@0', 'C@3'])

上面是题目的例子有点难懂。
下面是我写的例子:

function a(b){ console.log(b) } var i=0; let throttled=throttle(a,5000);

setInterval(() => { throttled(i++); }, 1000);

//输出: 0 5 6 11 12 17 18 ....... //其实就是每次该调用的时候调用两次,其中有一次要保留上次参数。

>答案

// 题目上的答案 function throttle(func, wait) { let flag=true; let preArgs; return function(){ if(!flag){ preArgs=[...arguments]; }else{ flag=false; func.apply(this,arguments); setTimeout(() => { flag=true; if (preArgs) func.apply(this,preArgs) }, wait); } } }

//平常我们使用的节流 function myThrottle(func, wait) { let flag=true; return function(...args){ if(!flag) return; flag=false; func.apply(this,args); setTimeout(() => { flag=true; }, wait); } } //按照第二个例子输出为: 0 6 12 18 ......