1function animateFunction()
2{
3 //animate stuff
4 window.requestAnimationFrame(animateFunction);
5}
6window.requestAnimationFrame(animateFunction);
1/* Request Animation Frame By Gourav Khurana */
2
3
4https://flaviocopes.com/requestanimationframe/
5https://glitch.com/edit/#!/flavio-requestanimationframe-example?path=script.js%3A1%3A0
6https://glitch.com/edit/#!/flavio-settimeout-animation?path=script.js%3A54%3A4
1const element = document.getElementById('some-element-you-want-to-animate');
2let start, previousTimeStamp;
3
4function step(timestamp) {
5 if (start === undefined)
6 start = timestamp;
7 const elapsed = timestamp - start;
8
9 if (previousTimeStamp !== timestamp) {
10 // Math.min() is used here to make sure the element stops at exactly 200px
11 const count = Math.min(0.1 * elapsed, 200);
12 element.style.transform = 'translateX(' + count + 'px)';
13 }
14
15 if (elapsed < 2000) { // Stop the animation after 2 seconds
16 previousTimeStamp = timestamp
17 window.requestAnimationFrame(step);
18 }
19}
20
21window.requestAnimationFrame(step);
1/* Tells the browser that you wish to perform an animation and
2 requests that the browser call a specified function
3 to update an animation before the next repaint. */
4
5requestAnimationFrame(() => {
6 // some animation-related/dependent code here
7});
8
9/* The callback function is automatically passed a timestamp
10 indicating the precise time requestAnimationFrame() was called at.
11 requestAnimationFrame() returns a non-zero integer that can be passed into
12 cancelAnimationFrame() to cancel a requestAnimationFrame() call */
13
14/* Advantages over setTimeout(..., 1000/60) approach:
15 - The browser can optimize it, so animations will be smoother
16 - Animations in inactive tabs will stop, allowing the CPU to chill
17 - More battery-friendly */
18
19
20
21