Approach one:
function throttle(func, timeMs) {
let lastTime = 0;
return function() {
const now = new Date();
if (now - lastTime >= timeMs) {
func();
lastTime = now;
}
};
}
Approach two:
function throttle(func, timeMs) {
let waiting = false;
return function() {
if (!waiting) {
func();
waiting = true;
setTimeout(() => {
waiting = false;
}, timeMs);
}
}
}
One uses the timestamp to keep track of the call while the other uses timeout. Is one better than the other?