JavaScript can be used to animate elements on a webpage. The setInterval()
and requestAnimationFrame()
methods are commonly used for animations.
Here’s an example of how to animate a box across the screen using setInterval()
:
let box = document.getElementById("animateBox");
let position = 0;
let interval = setInterval(function() {
if (position < 300) {
position += 5;
box.style.left = position + "px";
} else {
clearInterval(interval);
}
}, 20);
Animate an object on your webpage to move in any direction (up, down, left, right) using JavaScript.
setInterval()
in JavaScript?requestAnimationFrame()
?setInterval()
?Answers: It repeatedly calls a function at specified intervals; it is more efficient for animations; clearInterval()
.