每秒添加x

时间:2014-09-15 20:55:06

标签: javascript jquery

我想从今天的日期开始每秒向计数器添加一个数字(X)。

变量
开始日期
结束日期
每秒添加的数字(X)

如果X为0.4,则计数器将如下所示:
2014年9月15日10:00:01:0.4
2014年9月15日10:00:02:0.8
2014年9月15日10:00:03:1.2

这应该持续一年。

我发现了这个问题,但每次访问该页面时都会从零开始:jQuery counter to count up to a target number

相反,我寻找的代码有时间作为参考。

我试图修改代码:

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

jQuery(function($) {
        $('.timer').countTo({
            from: 10000,
            to: 100000,
            speed: 50000000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });

我的数据是:

from: 10000, to: 100000, speed: 50000000

代码中缺少from日期变量。我不认为这是最有效的设置。顶部的描述更适合。

1 个答案:

答案 0 :(得分:0)

好的,根据评论,听起来你需要一个特定时间点的计数器到现在为止。

使用Date().getTime()函数完成它很简单,它以毫秒为单位给你时间。

如果你只需要一个带系数的秒计数器,你可以做一些简单的事情:

var start = new Date('15 september 2014 10:00:00').getTime()/1000 | 0;
var x = 0.4;

var el = document.getElementById('t');

setInterval(function(){
    var output = ((((new Date().getTime()/1000 - start) | 0) * x * 10) | 0) / 10;
    el.innerHTML = '<span>' + new Date() + '</span>' + output;
}, 1000);

请在此处查看:http://jsfiddle.net/bdu4na3t/1/

相关问题