The requestAnimationFrame method returns an integer ID which can be used to cancel the queued request using the cancelAnimationFrame(id) method. The animation callback function can also accept a timestamp value, which is the time elapsed in milliseconds since the web page was loaded.
The requestAnimationFrame() method only runs once. You can make it loop over-and-over again using a technique called recursion. Let's say you wanted to count from 0 up to 500, and update the UI each time.
requestAnimationFrame() The window. requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
Another reason requestAnimationFrame is so useful is the fact that it gives you a time variable which you can use to calculate the amount of time between frames. This is not something that setInterval will do and since setInterval is not 100% accurate it is very possible your animation will get messed up over time.
I have always thought that timestamp used by requestAnimationFrame is the same as usual timestamp in JavaScript, that is number of milliseconds since January 1st, 1970. Today I have captured the timestamps to verify and found that the RAF timestamp are probably measured since the start of page loading. What precisely are the timestamps measured from?
The test code:
<p id="output"></p>
var i = 0;
var start = null;
var times = [];
var dur = 5000;
function step(timestamp) {
if (start===null) start = timestamp;
times[i++] = timestamp;
if (timestamp-start<=dur) {
requestAnimationFrame(step);
} else {
document.getElementById('output').innerHTML = times.join('<br>');
}
}
requestAnimationFrame(step);
gives results like this:
158.52126457412882
183.12243595205535
199.52116819316421
...
in all RAF capable browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With