What’s up everyone? I’m wiring up a scroll-driven pixel-art parallax thing and trying to keep it smooth, but my throttled handler sometimes skips the final position so the UI “snaps” a beat later.
function throttle(fn, wait) {
let last = 0;
let trailingArgs = null;
let timer = null;
return function (...args) {
const now = performance.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
last = now;
fn.apply(this, args);
} else {
trailingArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
last = performance.now();
fn.apply(this, trailingArgs);
trailingArgs = null;
}, remaining);
}
}
};
}
How do you structure throttle so it stays responsive but guarantees the final scroll state gets applied without causing extra layout thrash?
Hari