What happens when return is executed in this code?
Let's go through it step by step. Probably gonna get something wrong but that's how I imagine it.
Everything starts with
window.requestAnimationFrame(main);
In browser's memory there's a LIST of function names, of what functions - if any - to call when browser is ready to do that frame. The function above just puts an entry in the list saying "browser, when you're about to do that frame, call the function named main". The function exists as soon as "main" is added to that LIST.
Your main function DOES NOT run at this point.
At some point in the future, could be right away, could be milliseconds, could be seconds later, when browser is about to do that frame, it looks up in the internal list to see if there's some callback function there and finds the "main" function there. So, the browser deletes the only entry from the internal LIST making the list empty and then launches main function and waits until the main function finishes to start rendering/drawing/whatever the frame.
Now you're inside the main function.
In the main function, you do .requestAnimationFrame again adding yourself (the main function) as callback function. The requestAnimationFrame looks up at that internal LIST and adds the main function as callback and exists. Now, control comes back to the main function which checks if enough time has passed since it last ran, and if not enough time has passed the main function just exists. If enough time has passed, the function updates the last time variable and runs the game logic by calling GameEngine();
After GameEngine() runs, the main function exists and the browser finally "paints" / renders/ draws the frame
After the browser finishes updating the frame, and maybe a few ms more (for example browser may do 60 fps which means one frame every 1000/60 = 16ms but finishes rendering the frame in ms, in this case browser may waits 15 ms doing nothing) it's time for browser to render another frame, so it looks again in that internal LIST and spots the entry which says it should call "main" function again, so it removes the entry from the list (making the list empty) and calls main function.
If the main function doesn't add itself to that internal LIST every time by using the requestAnimationFrame function, the internal LIST will be emptied and the main function will no longer be called.
I think what you don't understand is that requestAnimationFrame is sort of async, it just puts the function name in an internal list and exists, it doesn't launch the main function right there, the main function is queued to run at some point in the future when the browser is about to draw another frame.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now