The browser has an, how to say, an painting cycle. Every 16ms (i am not sure if its exactly 16ms) the browser does an repaint.
The problem that you have, is that your loop is already done before the next repaint cycle.
Here is an solution with async / await
:
You can create an function called readyToAnimate
it returns an promise that resolves the callback function of the requestAnimationFrame
.
The requestAnimationFrame
callback gets executed before the next repaint.
Now in your loop you can use await readyToAnimate()
. It will wait till the browser is ready for the next repaint.
x = document.getElementById("btn");
x.onclick = async function() {
for (let y = 0; y < 1; y += 0.1) {
await readyToAnimate();
x.style.transform = `translateX(${y * 200}px)`;
}
}
function readyToAnimate() {
return new Promise(res => requestAnimationFrame(res));
}
<button id='btn'>button</button>