Skip to content

Commit 1d8b813

Browse files
authored
Update README.md
Added definition and code for requestAnimationFrame question
1 parent b13c320 commit 1d8b813

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8842,6 +8842,23 @@ The execution context is created when a function is called. The function's code
88428842
**[⬆ Back to Top](#table-of-contents)**
88438843
88448844
466. ### What is the purpose of requestAnimationFrame method?
8845+
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.
8846+
```javascript
8847+
const element = document.getElementById("myElement");
8848+
function animate() {
8849+
let currentPosition = parseInt(window.getComputedStyle(element).left, 10);
8850+
8851+
// Move the element 2px per frame
8852+
currentPosition += 2;
8853+
element.style.left = currentPosition + 'px';
8854+
// If the element hasn't moved off-screen, request the next frame
8855+
if (currentPosition < window.innerWidth) {
8856+
requestAnimationFrame(animate);
8857+
}
8858+
}
8859+
// Start the animation
8860+
requestAnimationFrame(animate);
8861+
```
88458862
88468863
**[⬆ Back to Top](#table-of-contents)**
88478864

0 commit comments

Comments
 (0)