javascripthtmlgame-loop

Does setTimeOut(function,time) keeps creating load on function stack?


I am making a Snake game on my webpage using JavaScript and HTML. In this game I want to call a function after regular time intervals. This function will update and print the position of the snake.

For this I am using setTimeOut(my_function,time).

My code looks like this

function my_function(){
// update values
// display snake
setTimeOut(my_function,time)
}

My question is - Will the above code create a lot of function calls on the function stack like a recursive function. I think it will.

Below is how I think I can optimise it.

function empty_function{
}

while(true){
//update values
//display snake
setTimeOut(empty_function,time)
} 

Will this method will also create a lot of function calls on the function stack like a recursive function?


Solution

  • Your optimized solution is actually the one that will crash the program, because it keeps the same function running forever. Your first approach is perfectly fine: setTimeout doesn't call the function immediately but schedules it to be run. In the meantime your process can handle other events and start with a new stack when your function is due to be called.
    In your infinite while loop your function will never even be called, as there will never be time for the program to check its scheduled task list.

    If your interval is frame based (for example, you wish to update your graphics as often as possible) you might be better off with requestAnimationFrame():

    function update(timestamp) {
      // render your game
      // request this function to be run again on the next frame:
      window.requestAnimationFrame(update);
    }
    
    window.requestAnimationFrame(update);
    

    As you can see it uses the same approach, but is specifically designed to try and match the refresh rate of the users screen freeing you from having to define the interval between render ticks.