JavaScript 是否提供高分辨率计时器? [英] Does JavaScript provide a high resolution timer?

查看:16
本文介绍了JavaScript 是否提供高分辨率计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript 是否提供高分辨率计时器?

Does JavaScript provide a high resolution timer?

我从头开始编写了一些游戏引擎,有些是用 C 语言编写的,有些是用 Java 编写的,有些是用 Flash 编写的.在动画和交互式图形方面,我始终遵循相同的基本模型.使用以下设计创建一个基本类/结构:

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);
    }
}

时间对于流畅的动画和游戏状态计算非常重要.在本机代码 Windows 中,我使用 QueryPerformanceCounter()QueryPerformanceFrequency() 在每个游戏循环中执行 queryTime() 的作用并通过更新/渲染的时间.在 Java 中,我使用 System.nanoTime().

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().

JavaScript 中的等价物是什么?也就是说,像 queryTime() 这样的函数返回一个高精度的时间值(亚毫秒).据我所知,您在 JavaScript 中可以获得的最佳准确度约为 15 毫秒……这对于动画来说太可怕了.

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.

推荐答案

参见 @h3r3 的答案——这是正确的回答.

毫秒是您在 JavaScript 中所能期望的最佳时间.而且,就像你说的,它不是很准确.请参阅堆栈溢出问题JavaScript 中的微秒计时.

See @h3r3's answer—it is the correct answer.

Milliseconds are the best you can hope for in JavaScript. And, like you said, it isn't very accurate. See Stack Overflow question Microsecond timing in JavaScript.

timer.js 声称提供高达微秒的分辨率,但它仅适用于谷歌浏览器.

timer.js purports to provide up to microsecond resolution, but it is only available for Google Chrome.

更新:timer.js支持微秒分辨率.它只是将毫秒计数乘以 1000.

Update: timer.js does not support microsecond resolution. It just multiplies millisecond count by 1000.

抱歉,没有更好的消息了!

Sorry, there isn't better news!

这篇关于JavaScript 是否提供高分辨率计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆