Why does "if condition" executes in this below code-Javascript-requestAnimationFrame

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shivajikobardan
    New Member
    • Jun 2022
    • 12

    Why does "if condition" executes in this below code-Javascript-requestAnimationFrame

    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.

    Code:
    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:
    "If condition" should never be checked on this code. Because:
    1) window.requestA nimationFrame(m ain): 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.


    But I asked chatGPT, and it says that if condition will be executed.

    It says that it doesn't immediately call the main function but schedule/queue it.

    What's this behavior called in Javascript language? Where can I read more about it. Is this common for every programming language?

    Things I've read from chatGPT

    requestAnimatio nFrame is a method that schedules a function to be called before the next repaint of the browser window. It does not immediately call the function, but rather adds it to a queue of functions to be called at a later time. This allows the browser to update the screen at a consistent frame rate, while also allowing other tasks to be performed in between frames.
Working...