JavaScript倒计时类

本文介绍了一种使用javascript内置定时器jtimer实现时间倒计时的方法,包括设置结束时间、生成回调函数以及启动和停止定时器的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(function (){
    var jtimer = function() {
        // init
        if(arguments.length >= 1) {
            this.setEndTime(arguments[0]);
        }
        if(arguments.length >= 2) {
            this.setGenerateCallBack(arguments[1]);
        }
    };
    jtimer.prototype.setEndTime = function () {
        if(arguments.length == 1) {
            this.endTime = arguments[0]; // Date
        }
    }
    jtimer.prototype.getMillisecond = function () {
        return this.endTime.getTime() - new Date().getTime();
    };
    jtimer.prototype.setGenerateCallBack = function (callback) {
        if(typeof callback == "undefined") return;
        this.generateCallBack = callback;
    }
    jtimer.prototype.generate = function () {
        if(typeof this.generateCallBack == "undefined") return;
        var ms = this.getMillisecond();
        this.generateCallBack(
            Math.floor(ms/(1000 * 60 * 60 * 24)),
            Math.floor(ms/(1000*60*60)) % 24,
            Math.floor(ms/(1000*60)) % 60,
            Math.floor(ms/1000) % 60
        );
    };
    jtimer.prototype.start = function () {
        var delay = 1000;
        if(arguments.length == 1) {
            delay = arguments[0];
        }
        _this = this; // for closure
        this.interval = window.setInterval(
            function() {
                _this.generate();
            }, delay);
    }
    jtimer.prototype.stop = function () {
        if(typeof this.interval == "undefined") return;
        window.clearInterval(this.interval);
        this.interval = undefined;
    }

    window.jtimer = jtimer;
})();


var jt = new jtimer(new Date("6/27/2016"), function (day, hour, min, sec) {
    console.log(day + "," + hour + "," + min + "," + sec);
});
jt.start(1000);

 

转载于:https://www.cnblogs.com/TLightSky/p/4063748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值