I'm trying to understand everything that is happening in this little code example in Eloquent Javascript: The Document Object Model (Chapter 13), but I'm not clear on where exactly the value for "time" is being passed into the animate() function before the function itself gets passed into requestAnimationFrame(). What exactly am I missing here?
<p style="text-align: center">
<img src="img/cat.png" style="position: relative">
</p>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
function animate(time) {
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
When you execute this line:
requestAnimationFrame(animate);, the functionanimatewill be called insiderequestAnimationFrameand will get thetimevariable passed as an argument. Something like this (narrowed and rough):Of course that
requestAnimationFramedoes not look at all like the function above, but this is just to illustrate wheretimecomes from.As per the documentation:
Read more here: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame