我不确定我是否得到了这个问题,但也许这会有所帮助?
要获取自上次运行函数以来的时间,您可以执行以下操作:
var lastTime = Date.now();
function update(){
//do stuff here
var myTime = Date.now(),
timePassed = myTime - lastTime; //time passed since last time
lastTime = Date.now(); //set for next time
}
要查看函数每秒运行多少次,您可以执行以下操作:
var lastTime = Date.now(), framerate=1;
function update(){
//do stuff
framerate++;
if ((Date.now()-1000)>lastTime) { //if a second or more has passed
console.log(framerate); //log number of times function has ran
framerate=0; //and reset values
lastTime = Date.now();
}
}
要加入这些功能,请执行以下操作:
var lastTimeEach = Date.now(), lastTimeSecond = Date.now(), framerate=1, x=480;
function update(){
//do game logic
var myTime = Date.now(), //time now
timePassed = myTime - lastTimeEach; //time passed since last iteration
lastTimeEach = Date.now(); //reset for next iteration
framerate++;
if ((myTime-1000)>lastTimeSecond) { //one second has passed
x += 480; //add 480 to x
framerate=0; //reset framerate
lastTimeSecond = Date.now(); //reset for next second
}
}
这是一个演示