Skip to main content
0:02est. 6 min

Throttle

// https://docs.google.com/document/d/1hvEjK5ZXMPYOr9HFoeCD4FM4b2dw-XsCwyB45M6Sz8Y/edit
// https://medium.com/javascript-in-plain-english/understanding-debouncing-throttling-2a0a5e9cc74a
// The throttle pattern restricts the maximum number of times that a function can be called.
// This method is usually used to control resizing, scrolling, and mouse-related events.
// Example: Execute this function at most once every 1000 milliseconds.
// throttle: Guaranteeing a constant flow of executions every X milliseconds.
// Like checking every 200ms your scroll position to trigger a CSS animation.


let flag = true;
const throttle = (fn, limit) => {
console.log('called', flag);
return function () {
if (flag) {
fn.apply(this, arguments)
flag = false;
setTimeout(() => {
flag = true;
console.log('changed');
}, limit)
}

}
}

const sum = (x) => {
console.log(x+1)
}

// async function wait(time) {
// return new Promise((resolve) => {
// setTimeout(()=> {
// resolve(true);
// }, time);
// });
// }

const doSum2 = sum(2);

const doSum3 = sum(3);

function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
// async function start() {
// setInterval(throttle(doSum,1000), 100);
throttle(doSum2, 1000);
// console.log('waiting start')
// sleep(3000)
// console.log('waiting end')
throttle(doSum3, 100);
// wait(2000)
// }

// start();

const throttle = (fn, delay) => {
let flag = true;
return function () {
if (flag) {
fn.apply(this, arguments);
flag = false;
setTimeout(() => {
flag = true;
}, delay)
}
}
}