Throttle with a trailing call
JavascriptRuns at most once per interval but still fires once more after the last event, so the final state is never dropped.
function throttle(fn, wait = 100) {
let last = 0;
let timer;
return (...args) => {
const now = Date.now();
const remaining = wait - (now - last);
clearTimeout(timer);
if (remaining <= 0) {
last = now;
fn(...args);
} else {
timer = setTimeout(() => { last = Date.now(); fn(...args); }, remaining);
}
};
}