Web Analytics Made Easy -
StatCounter What happens when return is executed in this code? - CodingForum


No announcement yet.

What happens when return is executed in this code?

  • Filter
  • Time
  • Show
Clear All
new posts

  • What happens when return is executed in this code?

    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.

    let speed = 2;
    let lastPaintTime = 0;
    //Game functions
    function main(ctime) {
    if ((ctime - lastPaintTime) / 1000 < 1 / speed) {
    lastPaintTime = ctime;
    //Main logic starts here
    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?

  • #2
    My confusion has been added up. Here's a new post.

    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.


    • #3

      This figure from this blog helped me clear my concepts related to this.

      Source: https://nainacodes.com/blog/understa...-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.

      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.

      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.

      4) Again, it calls window.rAF(main).

      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.

      main() gets executed.


      • #4
        ChatGPT is a AI's wonder. I'm solving a lot of coding problems with chatgpt