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
 

What is the purpose of the "return" statement in code?

The "return" statement is used to end the execution of a function and return a value to the caller. It can also be used to pass multiple values or to break out of a loop.

What happens when "return" is executed in a function?

When "return" is executed, the function stops executing and the value after the "return" keyword is passed back to the caller. The function's return value can then be used in other parts of the code.

Can "return" be used in any type of function?

Yes, "return" can be used in any type of function, including named functions, anonymous functions, and arrow functions. It is a fundamental part of how functions work in JavaScript.

What is the difference between "return" and "console.log()"?

The "return" statement is used to pass a value back to the caller of a function, while "console.log()" is used to print a value to the console for debugging purposes. "return" is an essential part of the function's functionality, while "console.log()" is used for logging and troubleshooting.

What happens if there is no "return" statement in a function?

If there is no "return" statement in a function, the function will still execute, but it will not return any value to the caller. The function will simply end and any code after the function call will continue to execute.

Similar threads

  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
23
Views
2K
  • Programming and Computer Science
Replies
1
Views
880
  • Programming and Computer Science
Replies
16
Views
1K
  • Programming and Computer Science
Replies
5
Views
885
  • Programming and Computer Science
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Programming and Computer Science
Replies
30
Views
4K
Back
Top