Search code examples
javascriptrequestanimationframe

How works requestAnimationFrame?


I am newbie to programming and faced with this function:

function update(time = 0) {
    console.log(time);
    requestAnimationFrame(update);
};
update();

Why in the function we declare the argument "time = 0" but when we declare this function do it without arguments?

In what moment requestAnimationFrame assign new value to variable time?


Solution

  • The variable time is has been set a default value of 0. Normally, the default value of a function parameter is undefined, but when declaring a function parameter with param=default_val, the parameter will instead default to the default_val if the function is invoked without the parameter or if the parameter is undefined. See Javascript Default Function Parameters.

    The callback function passed to requestAnimationFrame is given a single argument, which is the time at which it was called.

    Time will be 0 when update is first called because it was not passed as a parameter to requestAnimationFrame. After it is first called, the function passes itself as a callback to requestAnimationFrame and then the update function will be invoked with the time parameter, so it won't be set to 0.

    function update(time = 0) {
        console.log('time:', time, 'elapsed time ms:', time-start);
        if(time-start<=500){
        requestAnimationFrame(update);
        }
    };
    var start = performance.now();
    update();

    A better way to write this code would be to use requestAnimationFrame to call update instead of manually executing it. This way, the first time the update function is called, it will have the correct value of time, rather than it being 0 (and there will be no need for default function parameters for the update function).

    function update(time) {
        console.log(time);
        requestAnimationFrame(update);
    };
    requestAnimationFrame(update);