Giter Site home page Giter Site logo

countdown's People

Contributors

chaojidan avatar

Stargazers

 avatar

Watchers

 avatar

countdown's Issues

一个倒计时程序

特点:
1.可以指定一个标准的初始时间,通常这个时间是从服务器获取的,这样可以避免客户端本地时间不准确造成的问题
2.提供两个事件回调,每次倒计时时的回调(intervalCallback)和倒计时结束以后的回调(endCallback)

(function(global, undefined) {
    "use strict";
    //倒计时
    var Class = function() {
        var klass = function() {
            this.init.apply(this, arguments);
        };
        klass.fn = klass.prototype;
        klass.fn.init = function() {};
        return klass;
    };

    var Countdown = new Class;

    Countdown.fn.init = function(options) {
        this.interval = parseInt(options.interval, 10) > 0 ? parseInt(options.interval, 10) : 1000;
        this.timer = 0;
        this._getDiffTime(options.standardTime);
        this._getTargetTime(options.targetTime);
        this.intervalCallback = options.intervalCallback;
        this.endCallback = options.endCallback;
    };

    Countdown.fn.start = function() {
        var self = this;
        self.timer = setInterval(function() {
            self._countdown();
        }, self.interval);
    };

    Countdown.fn.stop = function() {
        var self = this;
        clearInterval(self.timer);
        if (typeof self.endCallback === 'function') {
            self.endCallback();
        }
    };

    Countdown.fn._getTargetTime = function(_targetTime) {
        if (_targetTime instanceof Date) {
            this.targetTime = options.targetTime;
        } else {
            this.targetTime = new Date(_targetTime);
        }
        if (utils.isValidDate(this.targetTime)) {
            if (this.targetTime < new Date().getTime()) {
                throw new Error('Countdown : Target time can not be less than the current time');
            }
        } else {
            throw new Error('Countdown : Invalid Date of "options.targetTime"');
        }
    };

    Countdown.fn._getDiffTime = function(_standardTime) {
        this.diffTime = 0;
        if (_standardTime !== undefined) {
            var standardTime;
            if (_standardTime instanceof Date) {
                standardTime = _standardTime;
            } else {
                standardTime = new Date(_standardTime);
            }
            if (utils.isValidDate(standardTime)) {
                this.diffTime = standardTime.getTime() - new Date().getTime();
                //console.log('diffTime:' + this.diffTime);
            } else {
                throw new Error('Countdown : Invalid Date of "options.timestamp"');
            }
        }
    };

    Countdown.fn._countdown = function() {
        var self = this;
        var currTime = new Date().getTime() + self.diffTime;
        //console.log(currTime);
        if (currTime < self.targetTime) {
            var leftMTime = self.targetTime - currTime, //剩余毫秒
                leftTime = utils.getLeftTime(leftMTime),
                strLeftTime = utils.getStrLeftTime(leftTime);
            //console.log('剩余', leftMTime);
            if (typeof self.intervalCallback === 'function') {
                self.intervalCallback(strLeftTime, leftTime);
            }
        } else {
            self.stop();
        }
    };


    var utils = {
        getStrLeftTime : function(leftTime) {
            var str_hour   = leftTime.h < 10 ? "0" + leftTime.h : leftTime.h,
                str_minute = leftTime.m < 10 ? "0" + leftTime.m : leftTime.m,
                str_second = leftTime.s < 10 ? "0" + leftTime.s : leftTime.s,
                text = str_hour + ":" + str_minute + ":" + str_second;
            if (leftTime.d > 0) {
                text = leftTime.d + "天 " + text;
            }
            return text;
        },
        getLeftTime : function(mtime) {
            var ms_per_day = 86400000, //24 * 60 * 60 * 1000
                e_days_left = mtime / ms_per_day,
                days_left = Math.floor(e_days_left),  //剩余天数
                e_hours_left = (e_days_left - days_left) * 24,
                hours_left = Math.floor(e_hours_left), //剩余小时
                e_minutes_left = (e_hours_left - hours_left) * 60,
                minutes_left = Math.floor(e_minutes_left), //剩余分钟
                seconds_left = Math.floor((e_minutes_left - minutes_left) * 60); //剩余秒
            return {
                d : days_left,
                h : hours_left,
                m : minutes_left,
                s : seconds_left
            }
        },
        isValidDate : function(d) {
            if ( Object.prototype.toString.call(d) !== "[object Date]" )
                return false;
            return !isNaN(d.getTime());
        }
    };

    global.Countdown = Countdown;
})(this);

使用方法:

var countdown = new Countdown({
    standardTime : '2012/08/01 20:00:00',  //服务器当前时间,如不指定则使用客户端当前时间
    targetTime : '2013/12/01 23:59:59',  //倒计时结束时间
    intervalCallback : function(str, arr) {  //str是一个格式化的倒计时字符串,arr是以数组形式存储的剩余时间
        $('#timer').text(str);
    },
    endCallback : function() {
        $('#timer').text('时间到');
    }
});
countdown.start();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.