Created
July 31, 2024 16:03
-
-
Save satyam4p/da66c4db505b5c4b65d8592d3e320ad0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Implement a throttler that executes an array of tasks. When the throttler is passed a number, only executes that number of the tasks and passes the other tasks into a queue. | |
//Throttling is a way/technique to restrict the number of function execution/calls. | |
/** | |
* normal throttle function | |
* @param {*} fn | |
* @param {*} delay | |
* @returns | |
*/ | |
function throttle(fn, delay) { | |
let lastRun; | |
let timer; | |
return function () { | |
if (!lastRun) { | |
fn.apply(this, arguments); | |
lastRun = Date.now(); | |
} else { | |
timer = setTimeout(function () { | |
if (Date.now() - lastRun > delay) { | |
fn.apply(this, arguments); | |
lastRun = Date.now(); | |
} | |
}, delay); | |
} | |
}; | |
} | |
/** | |
* THrottle array of tasks with given limit. It will execute the tasks with given limit of number in one go and then after the delay time is completed it should pickup next batch of size given limit should execute | |
* @param {*} tasks | |
* @param {*} delay | |
* @param {*} limit | |
*/ | |
function throttleTaskArray(tasks, delay, limit, callback) { | |
//ex: [1,2,3,4,5,6,7,8,9] | |
//limit 3 | |
let queue = [...tasks]; | |
let timer; | |
let lastExecuted; | |
return function () { | |
if (!lastExecuted) { | |
let execute = queue.splice(0, limit); | |
callback(execute); | |
lastExecuted = Date.now(); | |
} else { | |
clearTimeout(timer); | |
timer = setTimeout(function () { | |
if (Date.now() - lastExecuted > delay) { | |
const execute = queue.splice(0, limit); | |
callback(execute); | |
lastExecuted = Date.now(); | |
} | |
}, delay - (Date.now() - lastExecuted)); | |
} | |
}; | |
} | |
function createDOM() { | |
const btn = document.getElementById("click"); | |
const throttledMethod = throttleTaskArray( | |
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], | |
2000, | |
2, | |
(tasks) => { | |
console.log(tasks); | |
} | |
); | |
btn.addEventListener("click", throttledMethod); | |
} | |
createDOM(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment