countdown.js 1.64 KB
// 订单剩余时间显示及倒计时

require('../../common/bind-polyfill');

module.exports = {
    count: null,
    intervalTimer: null,
    intervalValue: 60000,
    $element: null,
    selector: '.left-time',
    addtionalMsg: '',
    showSec: false,
    setTime: function() {
        var that = this;

        this.$element.each(function(index, item) {
            var $item = $(item);
            var leftTime = $item.data('left');
            var i = that.intervalValue / 1000;

            $item.text(that.convertLeftTime(leftTime - that.count * i));
        });
        this.count += 1;
    },
    convertLeftTime: function(src) {
        var sec = parseInt(src, 10) % 60;
        var min = parseInt(src / 60, 10) % 60;
        var hour = parseInt(src / 3600, 10);
        var timeStr = min + '分';


        if (src <= 0) {
            timeStr = '已失效';
            return timeStr;
        }

        if (this.showSec) {
            timeStr += sec + '秒';
        }

        if (hour > 0) {
            timeStr = hour + '时' + timeStr;
        }

        timeStr = '剩余' + timeStr;

        if (this.addtionalMsg.length > 0) {
            timeStr += this.addtionalMsg;
        }

        return timeStr;
    },
    getLeftTime: function() {
        var that = this;

        if (this.$element.length) {
            this.setTime();
            this.intervalTimer = setInterval(this.setTime.bind(that), that.intervalValue);
        }
    },
    start: function() {
        this.count = 0;
        this.$element = $(this.selector);
        if (this.intervalTimer) {
            clearInterval(this.intervalTimer);
        }
        this.getLeftTime();
    }
};