Infinite loop
Proof that there is no end to what you can learn, here is an update to an article with a similar purpose, discovering something new.
There might come a time where you will rely on requestAnimationFrame to pull off a daring animation. The idea is to call a function which recursively calls itself with the mentioned API.
const animate = () => {
// ...
requestAnimationFrame(animate);
};
animate(); As soon as you invoke the function the browser executes the logic again and again, so that you are able to update the document over time. How much time? In the mentioned article I resolved to create a measure of progress based on two variables: counter and threshold.
let counter = 0;
const threshold = 500; With the two you increment the counter in the animating function. Making sure to reset the variable as soon as it reaches the threshold, you have a value which grows toward the larger number.
const animate = () => {
counter = (counter + 1) % threshold;
requestAnimationFrame(animate);
}; Divide the two and you have a number in the 0 to 1 range, which you can then map to your animating needs.
const t = counter / threshold; But again, how much time does it take for a complete iteration?
Considering that requestAnimationFrame is run as frequently as possible — let’s assume a refresh rate of 60 frames per second —, you can approximate an answer, but the truth is that the threshold is arbitrary, picked out of chance. The moment the animation takes too long, or too little, you can always update the upper limit.
-const threshold = 500;
+const threshold = 300; But as boldly prefaced, there is an alternative, leading to a more certain answer. Remember the animating function, passed as argument to requestAnimationFrame? Well, this callback function receives an argument itself, for the number of milliseconds elapsed since the beginning of the sequence.
const animate = (time) => {
// ...
requestAnimationFrame(animate);
}; With this in mind you don’t need a threshold, not even a counter. You need to describe a single variable for the duration.
const duration = 1000; The progress is then quick to realize. Round off the excess between the timestamp and the chosen measure with the modulo operator to have a number reaching for the duration. Divide the result by the same number of milliseconds and once again you have the convenient, 0 to 1 metric.
const t = (time % duration) / duration; That’s it. And there’s your answer. It takes as much time as you want it to take. You just have to make use of it.
- Progress
- 0.00
- Duration
- 1000