【问题标题】:Recurrent Javascript countdown循环 Javascript 倒计时
【发布时间】:2011-12-26 09:23:06
【问题描述】:

我有一个烦人的问题,我试图实现一个简单的 10 或 15 分钟循环倒计时。我已经尝试过 jQuery,但它只是让我可以选择倒计时到一个日期并在倒计时完成后停止。

我找到了下面的代码Here,但我想不出它来删除天数并让它倒计时 10 或 15 分钟。有人可以帮帮我吗?

<div id="countre3">Loading...</div>
<script type="text/javascript">
     function mycountre(o, timeArray){
         var countre = document.getElementById(o);
         if(!countre) {
             return;
         }

         // helper functions
         function mksec(day, h, m, s){ return day*24*60*60+h*60*60+m*60+s; }
         function toTimeString(sec, showZero){
             var d=Math.floor(sec/(60*60*24))
             var h=Math.floor(sec/(60*60)%24);
             var m=Math.floor((sec/60) % 60);
             var s=sec % 60;
             var ret=d+'days '+h+'hrs '+m+'min '+s+'sec';
             if(showZero){
                return ret;
             }else if(d==0 && h==0 && m==0){
                return s+'sec';
             }else if(d==0){
                return h+'hrs '+m+'min '+s+'sec';
             }else if(d==0 && h==0){
                return m+'min '+s+'sec';
             }else {
                return ret;
             }
         }
         //
         var secArray = [];
         var dayNow = new Date().getDay();
         for(var i=0;i<timeArray.length;i++){
            var day=timeArray[i][0];
            if(day==-1){
                day=dayNow;
            }
             secArray.push({
                day: timeArray[i][0],
                sec: mksec(day, timeArray[i][2], timeArray[i][2], timeArray[i][3]),
                msg: timeArray[i][4] || false,
                showZero: timeArray[i][5] || false
             });
         }
         secArray.sort(function(a,b){ return a.sec-b.sec;});

         // timer code - will be called around each second (~1000 ms)
         function updatecountre(){
             // get current UTC time in seconds
             var d=new Date();
             var secNow = mksec(d.getDay(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
             // find next event
             var nextIndex=0;
             for(var i=0;i<secArray.length; i++){
                 var diff = secArray[i].sec-secNow;
                 if(diff>0){
                     nextIndex=i;
                     break;
                 }
             }
             //
             var diff=secArray[nextIndex].sec-secNow;
             var prevDiff=diff;
             if(diff<0){
                var dayDiff = 6-secArray[nextIndex].day;
                if(secArray[nextIndex].day == -1){
                    dayDiff=0;
                }
                diff=(dayDiff+1)*24*60*60-Math.abs(diff);
             }
             var str='';
             // get message if there is any set
             if(secArray[nextIndex].msg){
                 str=secArray[nextIndex].msg;
             }
             var timeString = toTimeString(diff, secArray[nextIndex].showZero);
             if(str.match('@{countre}')!=null){
                 str=str.replace(/@{countre}/, timeString);
             }else if(str.indexOf(' ')==0){ // message starts with space
                 str=timeString+str;
             }else{ // no specific hint where to put countre, so display it after message
                 str+=timeString;
             }
             countre.innerHTML=str;
        }

         setInterval(updatecountre, 1000);

     };
mycountre('countre3', [ [5, 5, 0, 0, '<center><b>Next Turns are Due in </b><p class="smalltext"> @{countre}</center>', false] ]);
</script>

【问题讨论】:

标签: javascript countdown


【解决方案1】:

试试这个:

    function mycountre(countdownId, countdownSeconds, countdownLooping){
    var countre = document.getElementById(countdownId); // get html element
    if (!countre) {
        return;
    }

    var target = new Date().getTime() + 1000 * countdownSeconds; // target time
    var intervalId; // id of the interval

    // update function
    function updatecountre(){
        var time = Math.floor((target - new Date().getTime()) / 1000); // countdown time in seconds
        if (time < 0) { // if countdown ends
            if (countdownLooping) { // if it should loop
                target += 1000 * countdownSeconds; // set new target time
                time = Math.floor((target - new Date().getTime()) / 1000); // recalculate current time
            } else { // otherwise
                clearInterval(intervalId); // clear interval
                time = 0; // set time to 0 to avoid displaying negative values
            }
        }

        // split time to seconds, minutes and hours
        var seconds = '0' + (time % 60);
        time = (time - seconds) / 60;
        var minutes = '0' + (time % 60);
        time = (time - minutes) / 60;
        var hours = '0' + time;

        // make string from splited values
        var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
        countre.innerHTML = str;
    }

    intervalId = setInterval(updatecountre, 200); // start interval to execute update function periodically
};
mycountre(
    'countre3', // id of the html element
    15 * 60, // time in seconds (15min here)
    true // loop after countdown ends?
);

工作演示:http://jsfiddle.net/Xv3jx/1/

【讨论】:

  • +1。请注意,OP 需要“循环倒计时”,因此在您测试时间小于零时,您可能需要重新开始计数(否则调用 clearInterval())。此外,如果您将间隔设置为明显小于一秒(例如 50 或 100 毫秒),您可以获得更平滑的外观,因为浏览器不一定会完全按照请求的间隔调用您的函数。
  • 我可以看到您的示例在 js fiddle 上运行良好,但我很难实现它。
  • 我在代码中添加了一些 cmets。 @nnnnnn cmets 之后我也做了一些小改动
  • @Lolo ,我看到了您的更改,但我仍然无法显示它。你是如何显示它的?
  • 正如您在 jsfiddle 上的演示中所见,您必须创建带有一些 id 的 html 标记并将此 id 传递给函数。在演示中有&lt;div&gt; id countre3 作为第一个参数传递给函数。
【解决方案2】:

jQuery 插件的小尝试 - 更通用,无需分钟/小时计算,以避免示例变得太大:

(function($) {
    $.fn.countdown = function(params) {
        this.each(function() { 
            container = $.extend({
                t: $(this),
                stepSize: 1000, // milliseconds
                duration: 3600, // seconds
                offset: 0,
                stepCallback: function() {},
                finishCallback: function() {},
                interval: function() {
                    if (this.offset>this.duration) {
                        this.finishCallback();
                    } else {
                        this.stepCallback();
                    }
                    this.offset += this.stepSize/1000;
                }
            }, params);
            setInterval(function() {
                container.interval();
            }, container.stepSize);
        });
        return this;
    };
})(jQuery); 

可用于:

$('.main').countdown({
    stepCallback: function() { console.log('step');}, 
    finishCallback: function() { console.log('done');} 
}); 

然后会像这样实现一个简单的倒计时:

$('.main').countdown({
    duration: 300,
    stepCallback: function() {
        var time = this.duration-this.offset
        var seconds = '0' + (time % 60);
        time = (time - seconds) / 60;
        var minutes = '0' + (time % 60);
        time = (time - minutes) / 60;
        var hours = '0' + time;
        var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
        $(this.t).html(str);
    }, 
    finishCallback: function() {  $(this.t).html('tadaaa'); } 
});

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    相关资源
    最近更新 更多