+ 2

How to makes two click have different throttle output

Hello guys, I have a problem for this throttle. I want like the throttle have delay 5secs then i click two times with delay 5 secs so the output would be First click out in 5 secs then the second click out in 10 secs. How to makes it different for this two click throttle. This is my code const throttle = (func, limit) => { let flag = true; return function() { if(flag) { func.apply(this, arguments); flag = false; setTimeout(() => flag = true, limit); } } }; const throttleDisplay = throttle(() => console.log("Hi"), 1000); for(let i=1; i<=1; i++) { window.addEventListener("click", () => { console.log("ok") setTimeout(throttleDisplay, i*3000); }); }

15th Dec 2022, 4:03 AM
Jansen Su
Jansen Su - avatar
1 Antwort
0
To modify the throttle function so that it delays the output for 5 seconds after each click, you can use the setTimeout function to schedule the output to be displayed after a delay. Here is an example of how you can modify the throttle function to achieve the desired behavior: const throttle = (func, limit) => { let flag = true; let clickCount = 0; // Add a counter for the number of clicks return function() { if (flag) { func.apply(this, arguments); flag = false; // Increment the click counter and set the timeout based on the number of clicks clickCount++; setTimeout(() => flag = true, limit + (clickCount - 1) * 5000); } } }; const throttleDisplay = throttle(() => console.log("Hi"), 1000); for (let i = 1; i <= 2; i++) { window.addEventListener("click", () => { console.log("ok"); setTimeout(throttleDisplay, i * 3000); }); }
18th Dec 2022, 6:33 AM
Chris
Chris - avatar