how to add animation in loop in JavaScript
Answers
◾The animation in loop of a Java script can be added by using two methods.
- ⚫ USING SET TIMEOUT
- ⚫ USING REQUEST ANIMATION FRAME
___________________________
◽The first way of creating the loop that comes to mind is to use window.setTimeout and call a function every 1/60th of a second to achieve 60fps.
⭐Here is the gist:
window.setInterval(() => {
// updateUI();
}, 1000 / 60);
◽The updateUI function will be responsible for updating the CSS.
◽Here is the full code to move a DOM element around.
const refreshRate = 1000 / 60;
const maxXPosition = 400;
let rect = document.getElementById('rect0');
let speedX = 1;
let positionX = 0;
window.setInterval(() => {
positionX = positionX + speedX;
if (positionX > maxXPosition || positionX < 0) {
speedX = speedX * (-1);
}
rect.style.left = positionX + 'px';
}, refreshRate);
__________________________
◽Another and cleaner way of creating a game loop is to use the requestAnimationFrame built in function.
◽requestAnimationFrame will call the next frame and will need to be called recursively once the UI has been updated.
⭐Here is the gist:
function step() {
// UpdateUI();
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
◽And here is the full code to move a DOM element around:
const refreshRate = 1000 / 60;
const maxXPosition = 400;
let rect = document.getElementById('rect1');
let speedX = 1;
let positionX = 0;
function step() {
positionX = positionX + speedX;
if (positionX > maxXPosition || positionX < 0) {
speedX = speedX * (-1);
}
rect.style.left = positionX + 'px';
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step)