将Javascript计数器从秒改为毫秒

时间:2013-08-13 01:02:38

标签: javascript milliseconds seconds

所以我正在摆弄这个我一周前发现的代码,因为它能够“有点”完成旧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>

我很确定这可以改为按毫秒计数,从而以每秒一定量的更快速度增加。

提前致谢!

1 个答案:

答案 0 :(得分:0)

在这一行:

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次。