// Asked in sumo logic, hotstar
// Implement basic throttling funtion in js?
// const throttleFnTimeBased = (fn, delay) => {
// const throttledFunction = throttleFnTimeBased((msg) => {
// console.log(msg, Date.now());
// throttledFunction("Call 1"); // Executes immediately
// throttledFunction("Call 2"); // Throttled
// throttledFunction("Call 3"); // Throttled
// setTimeout(() => throttledFunction("Call 4"), 1100);
// // Executes after 1.1 seconds
// setTimeout(() => throttledFunction("Call 5"), 900);
// setTimeout(() => throttledFunction("Call 6"), 2100);
// // Executes after 2.1 seconds
const throttleFnTimeBased = (fn, delay) => {
return function (...args) {
lastExecuted = Date.now();
// create new timer remaning time
timerId = setTimeout(() => {
if (Date.now() - lastExecuted >= delay) {
lastExecuted = Date.now();
}, delay - (Date.now() - lastExecuted));
const throttledFunction = throttleFnTimeBased((msg) => {
console.log(msg, Date.now());
throttledFunction("Call 1"); // Executes immediately
throttledFunction("Call 2"); // Throttled
throttledFunction("Call 3"); // Throttled
setTimeout(() => throttledFunction("Call 4"), 1100);
// Executes after 1.1 seconds
setTimeout(() => throttledFunction("Call 5"), 900);
setTimeout(() => throttledFunction("Call 6"), 2100);