The code below is intended to implement a throttle function in javascript but, for some reason is not working and the console.log(json)
is only printed once... Could anyone help me out?
function throttle(cb, delay) {
let shouldWait = false;
return function() {
if (shouldWait) return;
cb();
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, delay);
};
}
const fetchTodos = async() => {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => console.log(json));
};
const fetchTodosThrottled = throttle(fetchTodos, 1000);
for (let i = 0; i < 1000; i++) {
fetchTodosThrottled();
}