Search code examples
javascripthtmlhtml5-canvasgame-loop

What does date.now() 'then' does here? - Javascript


I've used this tutorial to help me out writing a simple JS game for my school assignment. However I am now looking at the gameloop and I have no clue how this particular function is working.

Here is the URL of the tutorial. The block of code you're looking for is at 8 "The main game loop" http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/

//Gameloop
var main = function () {
    //var with timestamp
    var now = Date.now();

    //where does 'then' come from? I never declared it.
    var delta = now - then;

    //next up it just calls another func and provides parameter delta divided by 1000 which is the amount of miliseconds in a second
    update(delta / 1000);
    //and it calls my render function
    render();

    //then it sets then back to Date.now()
    then = now;

    //No idea what this line does. still looking into it
    requestAnimationFrame(main);
};

Solution

  • I will try to explain what I understood from the code in the tutorial.
    A game often runs in a fixed framerate, like 60 frames per seconds (FPS).
    In the tutorial, that is not the case. Instead of having a fixed framerate and moving the character at a fixed distance in the update function, you have a delta variable used to calculate the distance.

    hero.y -= hero.speed * modifier; // modifier is (delta / 1000)
    

    Like the other answers said, then is set in the beginning, in the outer scope of the main function.

    // Let's play this game!
    var then = Date.now();
    reset();
    main();
    

    I will add that the tutorial is a little old (2011) and some details can be improved. For example, you can use performance.now() instead of Date.now() as reported by lighthouse.