Javascript 时间参数理解中的问题
我在理解函数Javascript 时间参数理解中的问题,javascript,Javascript,我在理解函数runAnimation中的time变量时遇到问题。 它的初始价值是什么?它的价值来自哪里 我正在控制台中运行“runAnimation”函数,但无法确定它是如何初始化其第一个值的 function runAnimation(frameFunc) { let lastTime = null; function frame(time) { console.log(`time in frame function is : ${time}`); if (lastTime !=
runAnimation
中的time
变量时遇到问题。
它的初始价值是什么?它的价值来自哪里
我正在控制台中运行“runAnimation”函数,但无法确定它是如何初始化其第一个值的
function runAnimation(frameFunc) {
let lastTime = null;
function frame(time) {
console.log(`time in frame function is : ${time}`);
if (lastTime != null) {
let timeStep = Math.min(time - lastTime, 100) / 1000;
if (frameFunc(timeStep) === false) return;
}
lastTime = time;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
function runLevel(level, Display) {
let display = new Display(document.body, level);
let state = State.start(level);
let ending = 1;
return new Promise(resolve => {
runAnimation(time => { // i am confused with this variable
state = state.update(time, arrowKeys);
display.syncState(state);
if (state.status == "playing") {
return true;
} else if (ending > 0) {
ending -= time;
return true;
} else {
display.clear();
resolve(state.status);
return false;
}
});
});
}
请帮助我了解此函数的工作原理。它来自于将函数作为回调函数并隐式传递时间戳的函数。在您的示例中,函数
frame
被定义并作为回调传递
回调
要在下次重新绘制时更新动画时调用的函数。回调函数被传递一个参数,一个类似于performance.now()返回的参数的DOMHighResTimeStamp,指示requestAnimationFrame()开始执行回调函数的时间点
[编辑]
我试图突出显示/跟踪时间
或传递时间值的位置
function runAnimation(frameFunc) { // (2) frameFunc is the callback
let lastTime = null;
function frame(time) { // (3) defining a callback for requestAnimationFrame
console.log(`time in frame function is : ${time}`);
if (lastTime != null) {
let timeStep = Math.min(time - lastTime, 100) / 1000; // (5) time used here
if (frameFunc(timeStep) === false) return; // (6) // value based on time passed here
}
lastTime = time;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame); // (4) this passes `time` as a param to it's callback `frame`
}
function runLevel(level, Display) {
let display = new Display(document.body, level);
let state = State.start(level);
let ending = 1;
return new Promise(resolve => {
runAnimation(time => { // (1) It is just the name of a parameter in the inline callback
state = state.update(time, arrowKeys); // (7) now time is defined when this callback is finally called
display.syncState(state);
if (state.status == "playing") {
return true;
} else if (ending > 0) {
ending -= time;
return true;
} else {
display.clear();
resolve(state.status);
return false;
}
});
});
}
请注意,MDN文章在这一部分有点错误,返回的时间戳不是来自
performance.now()
的时间戳,它只是一个类似的时间戳。现在浏览器确实降低了针对幽灵和熔毁攻击的计时器功能的精度(而rAF cb param仍然具有完全的精度),这一点更为正确。我确实编辑了MDN文章来修正这个小的不精确性。第4行中传递给time
的值是多少。以及从requestAnimationFrame
传递值的位置。当它被调用时,您向它传递一个回调,一段时间后它调用您的回调并向它传递一个时间值。