requestAnimationFrame
Use rAF for custom animations synchronized to the display refresh rate — smoother than setInterval or setTimeout.
Use rAF for custom animations synchronized to the display refresh rate — smoother than setInterval or setTimeout.
function animateScroll(target, duration = 500) {
const start = window.scrollY;
const distance = target - start;
const startTime = performance.now();
function step(time) {
const progress = Math.min((time - startTime) / duration, 1);
const ease = progress < 0.5 ? 2*progress*progress : -1+(4-2*progress)*progress;
window.scrollTo(0, start + distance * ease);
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
$("a[href^=#]").on("click", function(e) {
e.preventDefault();
animateScroll($($(this).attr("href")).offset().top - 80);
});
rAF callbacks receive a DOMHighResTimeStamp for frame-accurate easing calculations.