JavaScript:这个计时器可靠吗? [英] JavaScript: Is this timer reliable?

查看:22
本文介绍了JavaScript:这个计时器可靠吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我被介绍到了 JavaScript 中的 Web Workers 世界.这让我重新思考计时器.我曾经用丑陋的方式对计时器进行编程,就像这样.

Today I was introduced to the world of Web Workers in JavaScript. This made me rethink about timers. I used to program timers the ugly way, like this.

var time = -1;
function timerTick()
{
    time++;
    setTimeout("timerTick()",1000);
    $("#timeI").html(time);
}

我知道可以通过保存启动计时器的日期来改善这一点,但我从来不喜欢这样做.

I know this could be improved by saving the date when you start the timer, but I've never been a fan of that.

现在我想出了一个使用 Web Workers 的方法,我做了一些基准测试,发现它更可靠.由于我不是 JavaScript 专家,因此我想知道此函数是否正常工作或可能存在哪些问题,请提前致谢.

Now I came up with a method using Web Workers, I did a little benchmark and found it much more reliable. Since I am not an expert on JavaScript I would like to know if this function works correct or what problems it might have thanks in advance.

我的 JavaScript 代码(请注意我使用的是 JQuery):

My JavaScript code (please note I use JQuery):

$(function() {
    //-- Timer using web worker. 
    var worker = new Worker('scripts/task.js'); //External script
    worker.onmessage = function(event) {    //Method called by external script
        $("#timeR").html(event.data)
    };
};

外部脚本('scripts/task.js'):

The external script ('scripts/task.js'):

var time = -1;
function timerTick()
{
    time++;
    setTimeout("timerTick()",1000);
    postMessage(time);
}
timerTick();

您还可以在我的网站上观看现场演示.

You can also view a live demo on my website.

推荐答案

如果您想可靠地显示秒数,那么唯一可靠的方法是在开始时获取当前时间并使用计时器仅用于更新屏幕.在每个刻度上,您会获得当前时间,计算实际经过的秒数并显示出来.setTimeout()setInterval() 都不能保证或不能用于准确计算时间.

If you're trying to reliably display seconds ticking by, then the ONLY reliable way to do that is to get the current time at the start and use the timer ONLY for updating the screen. On each tick, you get the current time, compute the actual elapsed seconds and display that. Neither setTimeout() nor setInterval() are guaranteed or can be used for accurately counting time.

你可以这样做:

var start = +(new Date);
setInterval(function() {
    var now = +(new Date);
    document.getElementById("time").innerHTML = Math.round((now - start)/1000);
}, 1000);

如果浏览器变得忙碌并且计时器间隔不规则,您可能会在屏幕上看到稍微不规则的更新,但是当屏幕更新时经过的时间将保持准确.您的方法很容易在经过的时间内累积错误.

If the browser gets busy and timers are erratically spaced, you may get a slightly irregular update on screen, but the elapsed time will remain accurate when the screen is updated. Your method is susceptible to accumulating error in the elapsed time.

你可以在这里看到这项工作:http://jsfiddle.net/jfriend00/Gfwze/

You can see this work here: http://jsfiddle.net/jfriend00/Gfwze/

这篇关于JavaScript:这个计时器可靠吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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