requestAnimationFrame runs code before the next repaint, perfect for smooth animations.
function animate() {
element.style.left = position + "px";
position += 1;
if (position < 500) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
This syncs with the display refresh rate, typically fps.