【问题标题】:How to create a JQuery Clock / Timer如何创建一个 JQuery 时钟/定时器
【发布时间】:2020-08-11 16:56:27
【问题描述】:

我有一个简单的测验应用程序,我想在页面顶部显示一个漂亮的计时器/时钟,向用户显示他们已经完成了多长时间。 (如果我能以某种方式向他们展示一个用于 Total Quiz Time 的计时器,以及另一个用于 This Question Time 的计时器,那会更酷,但是一旦我有一个计时器工作,我应该能够弄清楚如何自己做。

我的问题是:

什么是使用 JQuery 显示简单计时器/时钟的好方法? (直接 JS 也可以)我知道如何检查时间,但是如何获得递增秒数?

我自己的搜索不断将我带到 JQuery 插件(我想推出自己的)以及“事件计时器”,这不是我想要的......

【问题讨论】:

    标签: javascript jquery timer clock


    【解决方案1】:

    您正在寻找 setInterval 函数,它每 x 毫秒运行一个函数。

    例如:

    var start = new Date;
    
    setInterval(function() {
        $('.Timer').text((new Date - start) / 1000 + " Seconds");
    }, 1000);
    

    【讨论】:

    • 给我 1.001 秒、2.001、3.001 等。从 10 秒开始,小数点就消失了。猜猜我们需要一个 round() 吗?
    • 这段代码看起来不错。 $('.Timer').text(Math.round((new Date - start) / 1000, 0) + " Seconds");
    【解决方案2】:

    SLaks 建议的 setInterval 正是我制作计时器所需的。 (谢谢老兄!)

    使用 setInterval 和 this great blog post 我最终创建了以下函数来在我的“box_header”div 中显示一个计时器。我希望这可以帮助其他有类似要求的人!

     function get_elapsed_time_string(total_seconds) {
      function pretty_time_string(num) {
        return ( num < 10 ? "0" : "" ) + num;
      }
    
      var hours = Math.floor(total_seconds / 3600);
      total_seconds = total_seconds % 3600;
    
      var minutes = Math.floor(total_seconds / 60);
      total_seconds = total_seconds % 60;
    
      var seconds = Math.floor(total_seconds);
    
      // Pad the minutes and seconds with leading zeros, if required
      hours = pretty_time_string(hours);
      minutes = pretty_time_string(minutes);
      seconds = pretty_time_string(seconds);
    
      // Compose the string for display
      var currentTimeString = hours + ":" + minutes + ":" + seconds;
    
      return currentTimeString;
    }
    
    var elapsed_seconds = 0;
    setInterval(function() {
      elapsed_seconds = elapsed_seconds + 1;
      $('#box_header').text(get_elapsed_time_string(elapsed_seconds));
    }, 1000);
    

    【讨论】:

    • 嘿,不要相信函数会每 1000 毫秒运行一次,你会失去同步。您需要存储您的开始日期并计算每次差异,如该问题的接受答案所示
    • @jvanderh - 在这种情况下,间隔需要缩小到 100 毫秒或 250 毫秒,否则可能会发生第二次跳跃(10、11、12、14、15...) .
    【解决方案3】:
    ################## JQuery (use API) #################   
     $(document).ready(function(){
             function getdate(){
                    var today = new Date();
                var h = today.getHours();
                var m = today.getMinutes();
                var s = today.getSeconds();
                 if(s<10){
                     s = "0"+s;
                 }
                 if (m < 10) {
                    m = "0" + m;
                }
                $("h1").text(h+" : "+m+" : "+s);
                 setTimeout(function(){getdate()}, 500);
                }
    
            $("button").click(getdate);
        });
    
    ################## HTML ###################
    <button>start clock</button>
    <h1></h1>
    

    【讨论】:

    • 太棒了!如果使用 jQuery(我这样做),则显示时钟的简单、直接的方式。我为任何有兴趣看到这一点的人创建了一个 jsfiddle。在这里查看...jsfiddle.net/smallworld/ng22Y/1
    • 太棒了。直而简单。感谢分享。
    【解决方案4】:

    两全其美怎么样?我将答案与 OP 的格式结合起来。

    function pretty_time_string(num) {
        return ( num < 10 ? "0" : "" ) + num;
      }
    
    var start = new Date;    
    
    setInterval(function() {
      var total_seconds = (new Date - start) / 1000;   
    
      var hours = Math.floor(total_seconds / 3600);
      total_seconds = total_seconds % 3600;
    
      var minutes = Math.floor(total_seconds / 60);
      total_seconds = total_seconds % 60;
    
      var seconds = Math.floor(total_seconds);
    
      hours = pretty_time_string(hours);
      minutes = pretty_time_string(minutes);
      seconds = pretty_time_string(seconds);
    
      var currentTimeString = hours + ":" + minutes + ":" + seconds;
    
      $('.timer').text(currentTimeString);
    }, 1000);
    

    【讨论】:

    • 在这种方法中,您需要更频繁地更新文本,因为由于回调触发时间的偏差,两个连续的调用可能会在同一秒结束,您会在显示中跳秒.为了安全起见,我使用 100 毫秒的更新间隔。
    • 似乎答案被合并到另一个线程中,并且没有直接回答这个问题。在我的回答中,我采用了原始功能并对其进行了简单的复制和粘贴。
    【解决方案5】:

    24 小时制:

    setInterval(function(){
    
            var currentTime = new Date();
            var hours = currentTime.getHours();
            var minutes = currentTime.getMinutes();
            var seconds = currentTime.getSeconds();
    
            // Add leading zeros
            minutes = (minutes < 10 ? "0" : "") + minutes;
            seconds = (seconds < 10 ? "0" : "") + seconds;
            hours = (hours < 10 ? "0" : "") + hours;
    
            // Compose the string for display
            var currentTimeString = hours + ":" + minutes + ":" + seconds;
            $(".clock").html(currentTimeString);
    
    },1000);
    

    // 24 hour clock  
    setInterval(function() {
    
      var currentTime = new Date();
      var hours = currentTime.getHours();
      var minutes = currentTime.getMinutes();
      var seconds = currentTime.getSeconds();
    
      // Add leading zeros
      hours = (hours < 10 ? "0" : "") + hours;
      minutes = (minutes < 10 ? "0" : "") + minutes;
      seconds = (seconds < 10 ? "0" : "") + seconds;
    
      // Compose the string for display
      var currentTimeString = hours + ":" + minutes + ":" + seconds;
      $(".clock").html(currentTimeString);
    
    }, 1000);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="clock"></div>

    【讨论】:

      【解决方案6】:

      如果您可以将 jQuery 与 Moment.js(伟大的库)一起使用,那么方法就是:

      var crClockInit1 = null;
      var crClockInterval = null;
      function crInitClock() {
          crClockInit1 = setInterval(function() {
              if (moment().format("SSS") <= 40) {
                  clearInterval(crClockInit1);
                  crStartClockNow();
              }
          }, 30);
      }
      
      function crStartClockNow() {
          crClockInterval = setInterval(function() {
              $('#clock').html(moment().format('D. MMMM YYYY H:mm:ss'));
          }, 1000);
      }
      

      使用crInitClock() 开始时钟初始化。这样做是为了同步秒数。如果没有同步,您将在半秒后启动 1 秒计时器,并且会比实际时间晚半秒。

      【讨论】:

        【解决方案7】:
        var eventdate = new Date("January 01, 2014 00:00:00");
        
        function toSt(n) {
         s=""
         if(n<10) s+="0"
         return s+n.toString();
        }
        
        function countdown() {
         cl=document.clock;
         d=new Date();
         count=Math.floor((eventdate.getTime()-d.getTime())/1000);
         if(count<=0)
           {cl.days.value ="----";
            cl.hours.value="--";
            cl.mins.value="--";
            cl.secs.value="--";
            return;
          }
         cl.secs.value=toSt(count%60);
         count=Math.floor(count/60);
         cl.mins.value=toSt(count%60);
         count=Math.floor(count/60);
         cl.hours.value=toSt(count%24);
         count=Math.floor(count/24);
         cl.days.value=count;    
        
         setTimeout("countdown()",500);
        }
        

        您好,我有一个类似的任务,其中涉及创建一个 Javascript 倒计时时钟。这是我使用的代码。将上述代码插入 标签之间。请记住,如果您没有用于显示时钟的 html,则仅拥有此 javascript 不会有太大作用。我会把html写给你。随心所欲地设计时钟。

        【讨论】:

          【解决方案8】:
              var timeInterval = 5;
              var blinkTime = 1;
              var open_signal = 'signal1';
              var total_signal = 1;
          
              $(document).ready(function () {
                  for (var i = 1; i <= total_signal; i++) {
                      var timer = (i == 1) ? timeInterval : (timeInterval * (i - 1));
          
                      var str_html = '<div id="signal' + i + '">' +
                                     '<span class="float_left">Signal ' + i + ' : </span>' +
                                     '<div class="red float_left"></div>' +
                                     '<div class="yellow float_left"></div>' +
                                     '<div class="green float_left"></div>' +
                                     '<div class="timer float_left">' + timer + '</div>' +
                                     '<div style="clear: both;"></div>' +
                                     '</div><div class="div_separate"></div>';
          
                      $('.div_demo').append(str_html);
                  }
          
                  $('.div_demo .green').eq(0).css('background-color', 'green');
                  $('.div_demo .red').css('background-color', 'red');
                  $('.div_demo .red').eq(0).css('background-color', 'white');
          
                  setInterval(function () {
                      manageSignals();
                  }, 1000);
              });
          
              function manageSignals() {
                  var obj_timer = {};
          
                  var temp_i = parseInt(open_signal.substr(6));
                  if ($('#' + open_signal + ' .timer').html() == '0')
                      open_signal = (temp_i == total_signal) ? 'signal1' : 'signal' + (temp_i + 1);
          
                  for (var i = 1; i <= total_signal; i++) {
                      var next_signal = (i == total_signal) ? 'signal1' : 'signal' + (i + 1);
          
                      obj_timer['signal' + i] = parseInt($('#signal' + i + ' .timer').html()) - 1;
          
                      if (obj_timer['signal' + i] == -1 && open_signal == next_signal && total_signal!=1) {
                          obj_timer['signal' + i] = (timeInterval * (total_signal - 1)) - 1;
          
                          $('#signal' + i + ' .red').css('background-color', 'red');
                          $('#signal' + i + ' .yellow').css('background-color', 'white');
                      }
                      else if (obj_timer['signal' + i] == -1 && open_signal == 'signal' + i) {
                          obj_timer['signal' + i] = (timeInterval - 1);
          
                          $('#signal' + i + ' .red').css('background-color', 'white');
                          $('#signal' + i + ' .yellow').css('background-color', 'white');
                          $('#signal' + i + ' .green').css('background-color', 'green');
                      }
                      else if (obj_timer['signal' + i] == blinkTime && open_signal == 'signal' + i) {
                          $('#signal' + i + ' .yellow').css('background-color', 'yellow');
                          $('#signal' + i + ' .green').css('background-color', 'white');
                      }
          
                      $('#signal' + i + ' .timer').html(obj_timer['signal' + i]);
                  }
              }
          </script>
          

          【讨论】:

            【解决方案9】:

            这是@SLaks 的答案,但使用的是纯 ES6 JavaScript。

            var start = new Date,
              $timer = document.querySelector('.Timer');
            
            setInterval(function(timestamp) {
                $timer.innerText = `${timestamp - start) / 1000} Seconds`;
            }, 1000);

            【讨论】:

              【解决方案10】:

              刚刚使用@Uday 的答案代码并构建了一个 hr:mm 的反向时钟

              只是在玩,所以想如果有人可能需要这个,所以在 cmets 中分享小提琴(不知道为什么 stackover flow 不允许我在此处粘贴链接)

              【讨论】:

                【解决方案11】:
                var timeInterval = 5;
                    var blinkTime = 1;
                    var open_signal = 'top_left';
                
                    $(document).ready(function () {
                        $('#div_top_left .timer').html(timeInterval);
                        $('#div_top_right .timer').html(timeInterval);
                        $('#div_bottom_right .timer').html(timeInterval * 2);
                        $('#div_bottom_left .timer').html(timeInterval * 3);
                
                        $('#div_top_left .green').css('background-color', 'green');
                        $('#div_top_right .red').css('background-color', 'red');
                        $('#div_bottom_right .red').css('background-color', 'red');
                        $('#div_bottom_left .red').css('background-color', 'red');
                
                        setInterval(function () {
                            manageSignals();
                        }, 1000);
                    });
                
                    function manageSignals() {
                        var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
                        var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
                        var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
                        var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;
                
                        if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
                        else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
                        else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
                        else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';
                
                        if (top_left_time == -1) {
                            if (open_signal == 'top_right') {
                                top_left_time = (timeInterval * 3) - 1;
                                $('#div_top_left .red').css('background-color', 'red');
                                $('#div_top_left .yellow').css('background-color', 'white');
                                $('#div_top_left .green').css('background-color', 'white');
                            }
                            else if (open_signal == 'top_left') {
                                top_left_time = timeInterval - 1;
                                $('#div_top_left .red').css('background-color', 'white');
                                $('#div_top_left .yellow').css('background-color', 'white');
                                $('#div_top_left .green').css('background-color', 'green');
                            }
                        }
                
                        if (top_right_time == -1) {
                            if (open_signal == 'bottom_right') {
                                top_right_time = (timeInterval * 3) - 1;
                                $('#div_top_right .red').css('background-color', 'red');
                                $('#div_top_right .yellow').css('background-color', 'white');
                                $('#div_top_right .green').css('background-color', 'white');
                            }
                            else if (open_signal == 'top_right') {
                                top_right_time = timeInterval - 1;
                                $('#div_top_right .red').css('background-color', 'white');
                                $('#div_top_right .yellow').css('background-color', 'white');
                                $('#div_top_right .green').css('background-color', 'green');
                            }
                        }
                
                        if (bottom_right_time == -1) {
                            if (open_signal == 'bottom_left') {
                                bottom_right_time = (timeInterval * 3) - 1;
                                $('#div_bottom_right .red').css('background-color', 'red');
                                $('#div_bottom_right .yellow').css('background-color', 'white');
                                $('#div_bottom_right .green').css('background-color', 'white');
                            }
                            else if (open_signal == 'bottom_right') {
                                bottom_right_time = timeInterval - 1;
                                $('#div_bottom_right .red').css('background-color', 'white');
                                $('#div_bottom_right .yellow').css('background-color', 'white');
                                $('#div_bottom_right .green').css('background-color', 'green');
                            }
                        }
                
                        if (bottom_left_time == -1) {
                            if (open_signal == 'top_left') {
                                bottom_left_time = (timeInterval * 3) - 1;
                                $('#div_bottom_left .red').css('background-color', 'red');
                                $('#div_bottom_left .yellow').css('background-color', 'white');
                                $('#div_bottom_left .green').css('background-color', 'white');
                            }
                            else if (open_signal == 'bottom_left') {
                                bottom_left_time = timeInterval - 1;
                                $('#div_bottom_left .red').css('background-color', 'white');
                                $('#div_bottom_left .yellow').css('background-color', 'white');
                                $('#div_bottom_left .green').css('background-color', 'green');
                            }
                        }
                
                        if (top_left_time == blinkTime && open_signal == 'top_left') {
                            $('#div_top_left .yellow').css('background-color', 'yellow');
                            $('#div_top_left .green').css('background-color', 'white');
                        }
                        if (top_right_time == blinkTime && open_signal == 'top_right') {
                            $('#div_top_right .yellow').css('background-color', 'yellow');
                            $('#div_top_right .green').css('background-color', 'white');
                        }
                        if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
                            $('#div_bottom_left .yellow').css('background-color', 'yellow');
                            $('#div_bottom_left .green').css('background-color', 'white');
                        }
                        if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
                            $('#div_bottom_right .yellow').css('background-color', 'yellow');
                            $('#div_bottom_right .green').css('background-color', 'white');
                        }
                
                        $('#div_top_left .timer').html(top_left_time);
                        $('#div_top_right .timer').html(top_right_time);
                        $('#div_bottom_left .timer').html(bottom_left_time);
                        $('#div_bottom_right .timer').html(bottom_right_time);
                    }
                

                【讨论】:

                  猜你喜欢
                  • 2012-04-06
                  • 2017-07-25
                  • 2017-05-10
                  • 2020-10-24
                  • 1970-01-01
                  • 2011-06-18
                  • 2022-12-24
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多