I currently trying to learn how to animation in javascript works and I got a little bit stuck. The blog that I am reading is https://javascript.info/js-animation and this pice of code just drives me crazy.
let prev = performance.now();
let times = 0;
requestAnimationFrame(function measure(time) {
document.body.insertAdjacentHTML(
"beforeEnd",
Math.floor(time - prev) + " "
);
prev = time;
if (times++ < 10) requestAnimationFrame(measure);
})
I cannot uderstand what the variable times is all about, why he use time in the Math.floor method and why prev = time. Thanks!
timesHere, times is used as a counter to call the requestAnimationFrame function 10 times:
if (times++ < 10) requestAnimationFrame(measure);
times is less than 10requestAnimationFrametimestime = prevtime holds the timestamp at the function call, with very high accuracy. This is then assigned to prev, which is presumably used to hold the timestamp during the previous function call
The reason for this is explained in the next section
Math.floor(time - prev)Here, time holds the time during the current function call with very high precision, and prev the time during the previous function call.
If you subtract prev from time, You'll get the amount of time elapsed between the two.
The Math.floor function then rounds this down to an integer, after which it is inserted into the body using the document.body.insertAdjacentHTML function.