游戏开始时,使用 获取时间戳new Date().getTime()
,并将其保存在变量中。定期(您可以使用 setInterval),将其与当前时间戳进行比较,并根据已经过去的时间采取行动。
我建议使用定时事件构建一个数组,并从计时器回调中检查其元素。像这样的东西:
var startTime = new Date().getTime();
// List of timed events
// (times are in milliseconds)
var events = [
{ time: 5000, text: "do something after 5 secs"},
{ time: 10000, text: "do something after 10 secs"},
{ time: 20000, text: "do something after 20 secs"}
];
// Check for events every second
setInterval(function() {
var timePassed = new Date().getTime() - startTime;
console.log("passed: " + timePassed + " milliseconds");
// Check all events
for(var i=events.length-1; i>=0; i--) {
// If an event has expired, remove it from the list,
// (and do whatever tou need to do)
if(events[i].time <= timePassed) {
// log the event text to the console
console.log(timePassed + "ms passed. " + events[i].text);
// remove from array
events.splice(i, 1);
}
}
}, 1000);
DEMO(打开浏览器控制台查看输出)。