which loops are better for simple animations in JS
Why?
copy❌
Answers
Answer: I am new to javascript, and trying to learn the basics before jumping to jQuery and all the other libraries, so I can understand what's going on (or be able to even try) I have tried to run a simple animation with a for loop, activated by onclick. There is a single div (id=demo), 4 classes of CSS for the div (up, down, left, right, all modifing the position:relative) and I want to make it move in a square motion.
Using set Timeout
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);
Using request Animation Frame
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:
Explanation: PLEASE MAKE ME THE BRAINLEIST