requestAnimationFrame回调中的时间戳不会更改

问题描述 投票:-1回答:1

我希望以两种方式保留一段时间戳,首先是我的呼叫,第二次是setinterval。但是对于forloop,时间戳在所有时间都是相同的[]数组???

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 ...]

编辑:以下更改不会影响时间[],始终相同的值

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);
}
javascript for-loop requestanimationframe
1个回答
2
投票

你的for (let k=1 ; k < 1111 ; k++) requestAnimationFrame(step);同时调用所有requestAnimationFrame,因此所有1110调用step都被安排用于下一个动画帧,因此它们同时被调用。

这将是为每个动画帧运行step函数1111次的设置。

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

requestAnimationFrame(step)

更改:

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

至:

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);
}

不会改变任何东西,循环需要多长时间。 JavaScript是单线程的。在循环运行时,不会在其间执行其他代码。因此,循环中的所有requestAnimationFrame(step);将始终排队等待相同的下一个动画帧。

© www.soinside.com 2019 - 2024. All rights reserved.