timestamp in callback requestAnimationFrame function

Hi Guys,
I am actually trying to understand the timestamp value calculation in the below code snippet (this is actually a paddle moving from left to right and the code is working all fine)

But i am still a bit confused with the return value it produces , like in the below code…

function gameLoop(timestamp){
    let deltaTime=timestamp- lastTime;
    lastTime = timestamp;
    ctx.clearRect(0,0,800,600);
// the update function will recalculate the x and y coordinate from where the new paddle will appear
    paddle1.update(deltaTime);
// the draw method will redraw the paddle with new x,y coordinates 
    paddle1.draw(ctx);
  
    requestAnimationFrame(gameLoop);
}
gameLoop();

so, the thing i am confused about is,
1- when the gameloop() fuction is called first, it will go through the gamLoop function with no parameter?, so will timestamp will be zero initially?
2- also how come requestAnimationFrame(gameLoop); will return a timestamp value (that will then be used by gameloop each time it get looped)?

really appreciate your help :slight_smile:
Thanks
Umair

When functions with parameters are called without arguments for those parameters, those parameters are set to undefined. So in that first gameLoop() call, timestamp is going to be undefined - something you don’t want since that will cause your calculations to result in NaN. In fact that first call (and second, for that matter) should not work.

This is how requestAnimationFrame() works. Just like callbacks you send to addEventListener() get called with an Event argument, so too do requestAnimationFrame() callbacks get called with a timestamp argument, at least when the function is called through requestAnimationFrame() and not manually as is the case with the gameLoop() at the bottom.

You can get the value of timestamp using performance.now(), so if you want to simulate that when calling gameLoop() yourself, you can.

gameLoop(performance.now());

Or, you can skip calling it yourself and pass it into requestAnimationFrame() so it will automatically get called with it.

requestAnimationFrame(gameLoop); // instead of gameLoop()