我在理解函数time
中的runAnimation
变量时遇到问题。
它的初始值是多少?其值来自何处?
我正在控制台中运行'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;
}
});
});
}
帮助我了解此功能的工作原理。
答案 0 :(得分:2)
它来自函数requestAnimationFrame
,该函数将函数用作回调并隐式地传递了时间戳。在您的示例中,函数frame
已定义并作为该回调传递。
回调
当需要更新动画以进行下一次重绘时调用的函数。向回调函数传递一个单独的参数DOMHighResTimeStamp,该参数类似于Performance.now()返回的那个参数,指示requestAnimationFrame()开始执行回调函数的时间点。
[编辑]
我试图突出显示/跟踪time
或传递时间值的地方
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;
}
});
});
}