What happens when return is executed in this code?

  • JavaScript
  • Thread starter shivajikobardan
  • Start date
  • Tags
    Code
In summary, the code utilizes window.requestAnimationFrame(main) to call the main function after the browser has finished rendering the current display frame and is ready for updates. This process repeats continuously, with the event loop checking if the call stack is empty before executing the next frame. This ensures smoother display changes and may be necessary for certain updates to the DOM to take effect.
  • #1
shivajikobardan
674
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
  • #2
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:
  • #3
1) window.requestAnimationFrame(main) is called.
2) Again inside main, window.requestAnimationFrame(main) is called.

So, the condition is never checked?
 
  • #4
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?
 
  • #5
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.
 
  • #6
Last edited:
  • #7
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.
 
  • #8
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
 
  • #9
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
 

FAQ: What happens when return is executed in this code?

What happens when return is executed in this code?

When the return statement is executed in a code, it immediately ends the execution of the function and returns the specified value to the caller. This means that any code after the return statement will not be executed.

Can a return statement have multiple values?

No, a return statement can only return a single value. However, you can return multiple values by using an array, object, or other data structures to encapsulate the values you want to return.

What happens if a return statement is not followed by a value?

If a return statement is not followed by a value, the function will return undefined by default. This is because every function in JavaScript returns a value, even if one is not explicitly specified.

Can a return statement be used outside of a function?

No, a return statement can only be used within the body of a function. Attempting to use a return statement outside of a function will result in a syntax error.

Can a return statement be used in a loop or conditional statement?

Yes, a return statement can be used within a loop or conditional statement. When a return statement is executed within a loop or conditional statement, it will immediately exit the loop or conditional block and return the specified value to the caller.

Similar threads

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