Timeline Class

Setting up the class

Okay, lets set up a class that do all of the tasks we just outlined.

This tutorial is going to name the class 'Timeline' since more animation functionality will be added to it in future tutorials.

class Timeline{}

Since the object only needs to compare two points in time (the current frame and the previous frame), it'll need to store those two values.

class Timeline
{
    constructor()
    {
        this.now
        this.then
    }
}

Getting the current time

Conveniently, javascript has a native method for getting the time: Date.now(). This returns the numer of milliseconds since January 1st, 1970. Why 1970? It's mostly boring reasons having to do with UNIX, which you can read more about here, if you're curious.

Aside: performance.now()

There's also performance.now() if you want to get a more precise timestamp value, but you probably don't need it for this tutorial.

Updating then and now

Cool, so now that you know what method will get you the time, it time to put it to use!

Start by adding it to your constructor, then you can make an update function to reassign the values.

class Timeline
{
    constructor()
    {
        this.now = Date.now()
        this.then
    }
    update()
    {
        this.then = this.now
        this.now = Date.now()
    }
}

Delta Time

Great! Now that there's a then and now being recorded, the difference between them (or the delta) can be found. All you have to do is make a function that subtracts then from now

class Timeline
{
    deltaTime()
    {
        return this.now - this.then
    }
}

Now you're ready to start integrating this with the rest of the animation!