3

I've been trying to research how to use requestAnimationFrame and I've ended up very confused.

According to Mozilla, if you have an animation function called 'step' that you call with requestAnimationFrame(step), step accepts an argument that is a number of milliseconds, a DOMHighResTimeStamp argument.

And yet every single example I've seen online of how to use requestAnimationFrame does not use this argument. Some examples insist that you can assume the step function will run 60 times a second, and so they don't use any time concepts at all. Others get their own "number of milliseconds" separate from the argument, by using new Date(); - I suppose it's easy enough to modify these examples to use the argument instead.

Is it ok to assume the function will run 60 times a second? Seems...unwise to me. Mozilla says "The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation", which doesn't make me comfortable with that assumption. Is there a reason why people are using their own new Date() way of getting milliseconds rather than using the argument?

TKoL
  • 13,158
  • 3
  • 39
  • 73

1 Answers1

1

Well, there were some other answers and comments before but for some reason people removed them. I ended up figuring out how to use the timestamp appropriately and posted an answer here

I'll copy the answer over:


I think I've found an answer for you. It's based on this library

First, I would just grab a function from that site

function inOutQuad(n){
    n *= 2;
    if (n < 1) return 0.5 * n * n;
    return - 0.5 * (--n * (n - 2) - 1);
};

Then, I would use a modified form of the example code, something like this

function startAnimation(domEl){
    var stop = false;

    // animating x (margin-left) from 20 to 300, for example
    var startx = 20;
    var destx = 300;
    var duration = 1000;
    var start = null;
    var end = null;

    function startAnim(timeStamp) {
        start = timeStamp;
        end = start + duration;
        draw(timeStamp);
    }

    function draw(now) {
        if (stop) return;
        if (now - start >= duration) stop = true;
        var p = (now - start) / duration;
        val = inOutQuad(p);
        var x = startx + (destx - startx) * val;
        $(domEl).css('margin-left', `${x}px`);
        requestAnimationFrame(draw);
    }

    requestAnimationFrame(startAnim);
}

I might change how 'stop' is calculated, I might write something to ensure that it ends on destx, etc, but that's the basic format

Showing it in this jsfiddle

I'm actually kinda proud of this one. I've been wanting to figure this out for a while. Glad I had a reason to.

TKoL
  • 13,158
  • 3
  • 39
  • 73