Does JavaScript provide a high resolution timer?
I've written a few game engines from scratch, some in C, some in Java, and some in Flash. I always follow the same basic model when it comes to animations and interactive graphics. Create a basic class/structure with the following design:
void init() { /* Called once, preload essential resources here. */ }
void update(double time) { /* Updates game/animation state using high resolution time. */ }
void render(double time) { /* Updates screen graphics using high resolution time. */ }
void run()
{
double time;
init();
while (!done)
{
time = queryTime();
update(time);
render(time);
}
}
Time is so important to smooth animations and game state calculations. In native code Windows, I use QueryPerformanceCounter()
and QueryPerformanceFrequency()
to perform the role of queryTime()
in each game loop and pass the time to update/render. In Java, I use System.nanoTime()
.
What's the equivalent in JavaScript? That is, some function like queryTime()
which returns a time value with a high degree of accuracy (sub millisecond). From what I've heard the best accuracy you can get in JavaScript is about 15 ms ... which is horrible for animation.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…