JavaScript What happens when return is executed in this code?

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Code
AI Thread Summary
The discussion centers around the behavior of the `main` function in a JavaScript game loop using `window.requestAnimationFrame`. When `return` is executed within `main`, it terminates that specific execution of the function but does not prevent it from being called again by the next frame request. The sequence of execution involves the browser calling `main` after rendering the current frame, allowing the condition within `main` to be checked each time it runs. This process continues indefinitely, creating a smooth game loop. Understanding this flow is crucial for managing animations and updates in JavaScript effectively.
shivajikobardan
Messages
637
Reaction score
54
TL;DR Summary
return statement.
I'm currently watching tutorials to build projects as I'm still not in a phase where I can carve a project that I want all on my own.
Currently, working on a snake game.

JavaScript:
let speed = 2;
let lastPaintTime = 0;

//Game functions
function main(ctime) {
  window.requestAnimationFrame(main);
  if ((ctime - lastPaintTime) / 1000 < 1 / speed) {
    return;
  }
  lastPaintTime = ctime;
  gameEngine();
}

//Main logic starts here
window.requestAnimationFrame(main);

My confusion:
What happens when return is executed in this code? According to chatGPT, the function terminates. I get that. But does that mean it won't be called again via "Main logic starts here" part?
 
Technology news on Phys.org
shivajikobardan said:
But does that mean it won't be called again via "Main logic starts here" part?
What do you think? If main is not called again under the "Main logic starts here" section, can you see when else it might be called?
 
Last edited by a moderator:
1) window.requestAnimationFrame(main) is called.
2) Again inside main, window.requestAnimationFrame(main) is called.

So, the condition is never checked?
 
shivajikobardan said:
So, the condition is never checked?
No, the condition is checked right after window.requestAnimationFrame(main) is executed. What does window.requestAnimationFrame(main) actually do? When does it cause main() to be called?
 
pbuk said:
No, the condition is checked right after window.requestAnimationFrame(main) is executed. What does window.requestAnimationFrame(main) actually do? When does it cause main() to be called?
window.requestAnimationFrame(main) calls main function and main functoin calls window.requestAnimationFrame(main) which again calls main function. main function is called forever like that.
 
Last edited:
My confusion has now been added up.

My confusion:
"If condition" should never be checked on this code. Because:
1) window.requestAnimationFrame(main): It calls main function.
2) At the very first line of main function, it again calls main function. So the control should go to main function and forever it should keep calling itself.
3) The if condition should never be checked.
 
shivajikobardan said:
My confusion has now been added up.

My confusion:
"If condition" should never be checked on this code. Because:
1) window.requestAnimationFrame(main): It calls main function.
No it doesn't. Did you read #6?
pbuk said:
No it doesn't.

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

window.requestAnimationFrame(main) requests that the browser calls main()before the next repaint. [Edit - added] The browser will not attempt to do that until code executing in the current stack frame has completed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
 
Can you explain that with some diagrams and visualizations if they exist already? I'm still not getting it perfectly.
 
  • #10
Much of the time in JavaScript we write code that does not run straight away, it only runs if and when something else happens.

For instance a button's onclick handler runs when you click a button, a setTimeout callback runs when the timeout ends, and a promise's then handler runs when the promise resolves.

It is the same here: when we write window.requestAnimationFrame(main) main() is called when the browser has finished rendering the current display frame and is ready for you to make any updates you want to the DOM so it can render the next one. Note that the browser can only do one thing at a time, so it won't even start rendering the current display frame until your code stops.

So the sequence here is:
  1. Your script starts executing.
  2. main is defined starting on line 5.
  3. window.requestAnimationFrame(main) on line 15 tells the browser to call main when it is ready to render the next frame.
  4. Your script reaches the end and stops executing.
  5. The browser updates the display to match the DOM.
  6. The browser triggers the requestAnimationFrame event which calls main.
  7. window.requestAnimationFrame(main) on line 6 tells the browser to call main again when it is ready to render the next frame.
  8. The rest of the code in main runs, updating the DOM.
  9. Your script reaches the end of main and stops executing.
  10. Repeat from item 5 above.
 
Last edited:
  • Like
Likes shivajikobardan
  • #11
so basically, it runs after 16ms(at 60fps monitor? it's like set time out but better.
 
  • #12
shivajikobardan said:
so basically, it runs after 16ms(at 60fps monitor? it's like set time out but better.
More or less, yes. Often this is just cosmetic (display changes are smoother), but sometimes your code might not work properly without it (for example changing the height of a element will not alter the height of any containing element until after a repaint).
 
  • #13
This figure from this blog helped me clear my concepts related to this.
Source: https://nainacodes.com/blog/understand-the-event-loop-in-javascript

1) Initially, window.rAF is passed to call stack.

2) By definition, rAF waits till next repaint of window which is 16ms for 60fps screen. It's like setTimeOut but better.

WIkybL7pSaF8-VMxZFyTcVINEVMnayM8qgAJ7jcxK_38gjKOWw.png

3) window.rAF() is executed, so it is removed from the call stack. Call stack is empty. Meanwhile at the same time, after 16ms has been passed, main() has been put into callback queue.

R59MzPzCxQVbhNgtxDUGD7OpTrZKZg8KdlSMEbszlgPsiUV-9w.png


Now here is where the event loop comes in. The event loop is a continuous running process that constantly checks if the call stack is empty or not. If the call stack is empty, it will move the function from the callback queue into the call stack and it gets executed. So, main() gets executed.
PrH189cYU5OI7RpgbBKM0qZx02VhFmue89SDwQ-A64nUCHoYjQ.png

4) Again, it calls window.rAF(main).
WIkybL7pSaF8-VMxZFyTcVINEVMnayM8qgAJ7jcxK_38gjKOWw.png

window.rAF() has now executed.

5) Now, the code under window.rAF() runs(the if condition and so on and so forth). After, 16ms, main() is passed to callback queue.
R59MzPzCxQVbhNgtxDUGD7OpTrZKZg8KdlSMEbszlgPsiUV-9w.png


main() gets executed.
OyLQWnyenlkQItAfndMj8A92GhqmhDcmaN_mSD22Gr6lnKALeA.png
 

Similar threads

Replies
2
Views
1K
Replies
9
Views
1K
Replies
1
Views
2K
Replies
12
Views
4K
Replies
9
Views
2K
Replies
3
Views
3K
Replies
1
Views
1K
Back
Top