Search code examples
javascriptfor-looprequestanimationframe

timestamp does not change in requestAnimationFrame callback


i want keep a trace of timestamp in two manners, first i forloop the call, second with a setinterval. But with the forloop, the timestamp is the same in all the times[] array ???

var i = 0;
var i2=0;
var times = [];
var times2 = [];

function step(timestamp) {
   times[i++] = timestamp;
}

for (let k=1 ; k < 1111 ; k++) requestAnimationFrame(step);


function step2(timestamp) {times2[i2++] = timestamp;}

rAF = _ => requestAnimationFrame(step2);
const ID = setInterval(rAF,0);
setTimeout( _ => clearInterval(ID) , 200);

console.log(times); // [22.453 , 22.453 , 22.453 ,......] NEVER CHANGE !
console.log(times2); // [ 87.456 , 87.456 , 99.223 ...]

EDIT : following change does not affect times[], always same value

for (let k=1 ; k < 1111 ; k++) {
    for (let o=1 ; o < 11111111 ; o++) {} // i guess it put some delay between each call to requestAnimationFrame
    requestAnimationFrame(step);
}

Solution

  • Your for (let k=1 ; k < 1111 ; k++) requestAnimationFrame(step); calls all requestAnimationFrame at the same time, so all 1110 calls to step are scheduled for the next animation frame, and so they are called all at the same time.

    This would be a setup to run step function for each animation frame for 1111 times.

    function step(timestamp) {
       times[i++] = timestamp;
       if( i < 1111 ) {
          requestAnimationFrame(step)
       }
    }
    
    requestAnimationFrame(step)
    

    Changing:

    for (let k=1 ; k < 1111 ; k++) {
       requestAnimationFrame(step);
    }
    

    to:

    for (let k=1 ; k < 1111 ; k++) {
        for (let o=1 ; o < 11111111 ; o++) {} // i guess it put some delay between each call to requestAnimationFrame
        requestAnimationFrame(step);
    }
    

    does not change anything, it does not matter how long the loop takes. JavaScript is single threaded. As of that while the loop is running, no other code will be executed in between. So all requestAnimationFrame(step); within the loop will always be queued up for the same next animation frame.