JS Coding Questions Logo
JS Coding Questions
#469💼 Interview💻 Code

What is the purpose of requestAnimationFrame method?

Advertisement

728x90

The requestAnimationFrame() method in JavaScript is used to schedule a function to be called before the next repaint of the browser window, allowing you to create smooth, efficient animations. It's primarily used for animations and visual updates, making it an essential tool for improving performance when you're animating elements on the web.

javascript
1const element = document.getElementById("myElement");
2
3function animate() {
4
5let currentPosition = parseInt(window.getComputedStyle(element).left, 10);
6
7// Move the element 2px per frame
8
9currentPosition += 2;
10
11element.style.left = currentPosition + "px";
12// If the element hasn't moved off-screen, request the next frame
13
14if (currentPosition < window.innerWidth) {
15
16requestAnimationFrame(animate);
17}
18}
19// Start the animation
20
21requestAnimationFrame(animate);

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 41

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
469of476