活动开始和截止时间倒计时

一个活动,拥有开始时间结束时间,分别需要去执行相关的任务,公司的一些项目中用的还挺多,随手记录一下吧,便于以后用到。

代码如下:

(function($){
    $.actCountTimer=function(options){
        //各种属性、参数
        var defaults = {
            DurationTime:['20170109085500','20170119085500'], //活动开启和截止时间
            open:function(){}, //活动开始执行
            close:function(){} //活动结束执行
        };
        var _opt = $.extend(defaults,options);
        var startTimer=_opt.DurationTime[0],endTimer=_opt.DurationTime[1];
        var start_time=new Date(parseInt(startTimer.substr(0,4)),parseInt(startTimer.substr(4,2)),parseInt(startTimer.substr(6,2)),parseInt(startTimer.substr(8,2)),parseInt(startTimer.substr(10,2)),parseInt(startTimer.substr(12,2))),end_time=new Date(parseInt(endTimer.substr(0,4)),parseInt(endTimer.substr(4,2)),parseInt(endTimer.substr(6,2)),parseInt(endTimer.substr(8,2)),parseInt(endTimer.substr(10,2)),parseInt(endTimer.substr(12,2)));
        var start_timeMonth=start_time.getMonth()-1,end_timeMonth=end_time.getMonth()-1;
        start_time.setMonth(start_timeMonth);
        end_time.setMonth(end_timeMonth);
        _mainFun();
        function _mainFun(flag){
            var curr_time=new Date();
            if(flag){
                if(end_time>curr_time){
                    setTimeout(function(){
                        _mainFun(1);
                    },1000);
                }else{
                    _opt.close.call(this);
                }
            }else{
                if(start_time>curr_time){
                    setTimeout(function(){
                        _mainFun();
                    },1000);
                }else{
                    if(end_time>curr_time){
                        _opt.open.call(this);
                        setTimeout(function(){
                            _mainFun(1);
                        },1000);
                    }else{
                        _opt.close.call(this);
                    }
                }
            }
        }
    }
})(jQuery);

用法如下:

$.actCountTimer({
            DurationTime:['20170109105150','20180109105200'], //活动开启和截止时间
            open:function(){ //活动开始执行
                console.log('open');
            },
            close:function(){ //活动结束执行
                console.log('close');
            }
        });


猜你喜欢

转载自blog.csdn.net/xw505501936/article/details/54288105