【问题标题】:Changing Javascript Counter From Seconds To Milliseconds将 Javascript 计数器从秒更改为毫秒
【发布时间】:2013-08-13 01:02:37
【问题描述】:

因此,我正在摆弄我一周前发现的这段代码,因为它能够“在某种程度上”完成旧 gmail 文件计数器的外观。我未能使计数器以比每秒更快的速度准确增加。

通过编辑代码中最低的 1000 [在 setTimeout(function(){thisobj.start()}, 1000) 中找到],计数器的计数速度要快得多,但是在刷新时它会恢复到它开始时的位置附近秒或两秒(取决于从开始到刷新的时间)。

<html>
<head>
    <script type="text/javascript">
        function countup(startingdate, base) {
            this.currentTime = new Date();
            this.startingdate = new Date(startingdate);
            this.base = base;
            this.start();
        }

        countup.prototype.oncountup = function(){};

        countup.prototype.start = function() {
            var thisobj = this,            
                timediff = (this.currentTime-this.startingdate) / 1000,
                secondfield = Math.floor((timediff));
                result = { seconds: secondfield };

            this.currentTime.setSeconds(this.currentTime.getSeconds() + 1);
            this.oncountup(result);

            setTimeout(function(){
                thisobj.start();
            }, 1000);
        };
    </script>
</head>

<body>
    <div id="holder"></div>

    <script type="text/javascript">
        var startDate = new countup("August 3, 2013 18:59:00", "seconds") // Change starting Date Here

        startDate.oncountup= function(result) {
            var mycountainer = document.getElementById("holder");
            mycountainer.innerHTML =+ result['seconds'];
        }
    </script>
</body>
</html>

我相当肯定这可以更改为以毫秒为单位计数,从而以每秒一定数量的更快速度增加。

提前致谢!

【问题讨论】:

  • 如果您最初编写了代码,这应该是微不足道的或者是大量的工作。但是,浏览器将无法满足您的要求。
  • 这个问题似乎是题外话,因为它是关于修改提问者的代码(对未来的读者没有用)

标签: javascript milliseconds seconds


【解决方案1】:

在这一行:

this.currentTime.setSeconds(this.currentTime.getSeconds() + 1);

代码更新其currentTime,将其设置为向前一秒。该函数每秒执行一次,因此其效果就像获取当前时间一样。

如果您将其更改为每 0.5 秒运行一次,它会将秒数提前两倍,从而在您刷新页面时导致它倒退。如果你让它运行 3 秒,它会增加 6 秒,所以如果你重新加载它,那么在获取当前时间时时钟似乎会倒退 3 秒。

由于某种原因,代码没有通过调用new Date() 来获取当前日期(性能?内存管理?),因此您必须更改它如何将currentTime 向前移动以修复错误,以毫秒而不是秒为单位进行增量,如下所示:

    this.currentTime.setMilliseconds(this.currentTime.getMilliseconds()+500);
    var timediff=(this.currentTime-this.startingdate)/500;
    var secondfield=Math.floor((timediff));
    var result={halfSeconds:secondfield};
    this.oncountup(result);
    setTimeout(function(){thisobj.start()}, 500);

这将使它每 0.5 秒增加 1。

【讨论】:

    猜你喜欢
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多