【问题标题】:plain count up timer in javascriptjavascript中的普通倒计时计时器
【发布时间】:2011-04-01 18:53:38
【问题描述】:

我正在寻找一个简单的 javascript 计数计时器。我找到的所有剧本都是“唱歌跳舞”。我只想要一个免费的、最小的、以分钟和秒显示的计时器。谢谢。

【问题讨论】:

  • 正如我所说的一切,我发现它......太多了。我想要一些清淡的东西..
  • 从0开始,每秒增加1
  • var i=0,timer=setInterval(function(){i++},1000); - 瞧,它从 0 开始,每秒增加 1。

标签: javascript


【解决方案1】:

检查一下:

var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);

function setTime() {
  ++totalSeconds;
  secondsLabel.innerHTML = pad(totalSeconds % 60);
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}
&lt;label id="minutes"&gt;00&lt;/label&gt;:&lt;label id="seconds"&gt;00&lt;/label&gt;

【讨论】:

  • 我不推荐这种方法,因为它可能会延迟执行导致错误的值。更好的方法是基于系统时间的计时器。
  • 您的方法虽然在某些情况下可能不适合,但它是一种很好的方法,对我有用。非常感谢。
  • 有人可以向我解释一下为什么 React 可能更适合这样的事情吗?还是说 React 正在解决一个完全不同的问题?
  • 如何存储完成测验所用的时间。我刚刚在我现有的测验应用程序中添加了你的代码,现在我需要在单击完成按钮后存储时间值以及我需要显示时间的分数。你能帮我或给我任何链接的想法
【解决方案2】:

用于 jQuery 的计时器 - 更小、工作正常、经过测试。

    var sec = 0;
    function pad ( val ) { return val > 9 ? val : "0" + val; }
    setInterval( function(){
        $("#seconds").html(pad(++sec%60));
        $("#minutes").html(pad(parseInt(sec/60,10)));
    }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="minutes"></span>:<span id="seconds"></span>

纯 JavaScript:

    var sec = 0;
    function pad ( val ) { return val > 9 ? val : "0" + val; }
    setInterval( function(){
        document.getElementById("seconds").innerHTML=pad(++sec%60);
        document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
    }, 1000);
&lt;span id="minutes"&gt;&lt;/span&gt;:&lt;span id="seconds"&gt;&lt;/span&gt;

更新:

这个answer 展示了如何填充。

停止 setInterval MDN 是通过 clearInterval MDN

实现的
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );

Fiddle

【讨论】:

  • 谢谢...正是我想要的...+1。请注意那些想要为计时器添加小时数的人,您只需更改/添加以下代码: $("#minutes").html(timerCall(parseInt(sec/60,10)%60)); $("#hours").html(timerCall(parseInt(sec/3600,10)));
  • 不错。使用它。谢谢。什么是停止计时器而不重置数字的好方法?
  • setInterval 有它的“邪恶兄弟”clearInterval :) 来摧毁他。我还添加了一个示例
  • 对于那些需要几个小时的人也可以更改 js 并添加标签: $("#minutes").html(pad(parseInt(sec / 60 % 60, 10))); $("#hours").html(pad(parseInt(sec / 3600 % 60, 10)));
  • @Bakudan 为什么在 parseInt 部分使用 ,10。如果我删除它,它似乎给出了相同的结果。
【解决方案3】:

下面的代码用作倒数计时器。这是显示 hour:minute:second 的纯 JavaScript 代码。它还有一个停止按钮:

var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
           ++totalSeconds;
           var hour = Math.floor(totalSeconds /3600);
           var minute = Math.floor((totalSeconds - hour*3600)/60);
           var seconds = totalSeconds - (hour*3600 + minute*60);
           if(hour < 10)
             hour = "0"+hour;
           if(minute < 10)
             minute = "0"+minute;
           if(seconds < 10)
             seconds = "0"+seconds;
           document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
        }

    
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
        
        

【讨论】:

    【解决方案4】:

    我必须为教师为学生的作业评分创建一个计时器。这是我使用的一个,它完全基于自评分开始以来经过的时间,通过存储页面加载时的系统时间,然后每半秒将其与该点的系统时间进行比较:

    var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
    localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
    
    function startTimeCounter() {
        var now = Math.floor(Date.now() / 1000); // get the time now
        var diff = now - startTime; // diff in seconds between now and start
        var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
        var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
        m = checkTime(m); // add a leading zero if it's single digit
        s = checkTime(s); // add a leading zero if it's single digit
        document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
        var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
    }
    
    function checkTime(i) {
        if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
        return i;
    }
    
    startTimeCounter();
    

    这样,“setTimeout”是否受到执行延迟的影响并不重要,经过的时间总是相对于它刚开始时的系统时间,而系统时间在更新时间。

    【讨论】:

    • 这太棒了,与接受的答案相比,我计算了这个时间,在我的计算机上,接受的答案每 10 分钟大约 3 秒。这个版本应该会得到更多的支持。
    • 这应该是正确的答案。我相信任何寻找倒数计时器的人都在寻找这个。其他答案也有效,但如果您在某个时候离开窗口,似乎计时器已进入休眠状态,因此时间不会连续计数。
    【解决方案5】:

    在 stackoverflow 中摆弄 Bakudan 的代码和其他代码,以便将所有内容合二为一。

    更新 #1:添加了更多选项。现在开始、暂停、恢复、重置和重新启动。混合功能以获得所需的结果。

    更新 #2 : 编辑了以前使用的纯 JS 的 JQuery 代码并添加为代码 sn-p。

    对于以前基于 Jquery 的小提琴版本:https://jsfiddle.net/wizajay/rro5pna3/305/

    var Clock = {
      totalSeconds: 0,
      start: function () {
        if (!this.interval) {
            var self = this;
            function pad(val) { return val > 9 ? val : "0" + val; }
            this.interval = setInterval(function () {
              self.totalSeconds += 1;
    
              document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
              document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
            }, 1000);
        }
      },
    
      reset: function () {
        Clock.totalSeconds = null; 
        clearInterval(this.interval);
        document.getElementById("min").innerHTML = "00";
        document.getElementById("sec").innerHTML = "00";
        delete this.interval;
      },
      pause: function () {
        clearInterval(this.interval);
        delete this.interval;
      },
    
      resume: function () {
        this.start();
      },
    
      restart: function () {
         this.reset();
         Clock.start();
      }
    };
    
    
    document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });
    document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });
    document.getElementById("resumeButton").addEventListener("click", function () { Clock.resume(); });
    document.getElementById("resetButton").addEventListener("click", function () { Clock.reset(); });
    document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
    <span id="min">00</span>:<span id="sec">00</span>
    
    <input id="startButton" type="button" value="Start">
    <input id="pauseButton" type="button" value="Pause">
    <input id="resumeButton" type="button" value="Resume">
    <input id="resetButton" type="button" value="Reset">
    <input id="restartButton" type="button" value="Restart">

    【讨论】:

    • 不错的代码,我想知道如何重置计时器,因为 pause() 从它停止的地方继续。请帮忙!
    • @MuhFred 添加了重置和重启的选项。在这里摆弄jsfiddle.net/wizajay/cbpd0egz
    • 确实是好代码。只是想说我注意到如果您多次单击开始,计时器会加快速度。如果出现这种情况,可能不是人们想要的代码中的东西
    • @RohanKorde 不错的发现。我已经更新了答案,现在它先检查然后开始。
    【解决方案6】:

    从@Chandu 扩展,添加了一些用户界面:

    <html>
    <head>
    <script   src="https://code.jquery.com/jquery-3.2.1.min.js"   integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="   crossorigin="anonymous"></script>
    </head>
    <style>
    button {
    background: steelblue; 
    border-radius: 4px; 
    height: 40px; 
    width: 100px; 
    color: white; 
    font-size: 20px; 
    cursor: pointer; 
    border: none; 
    }
    button:focus {
    outline: 0; 
    }
    #minutes, #seconds {
    font-size: 40px; 
    }
    .bigger {
    font-size: 40px; 
    }
    .button {
      box-shadow: 0 9px #999;
    }
    
    .button:hover {background-color: hotpink}
    
    .button:active {
      background-color: hotpink;
      box-shadow: 0 5px #666;
      transform: translateY(4px);
    }
    </style>
    <body align='center'>
    <button onclick='set_timer()' class='button'>START</button>
    <button onclick='stop_timer()' class='button'>STOP</button><br><br>
    <label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
    </body>
    </html>
    <script>
    
    function pad(val) {
      valString = val + "";
      if(valString.length < 2) {
         return "0" + valString;
         } else {
         return valString;
         }
    }
    
    totalSeconds = 0;
    function setTime(minutesLabel, secondsLabel) {
        totalSeconds++;
        secondsLabel.innerHTML = pad(totalSeconds%60);
        minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
        }
    
    function set_timer() {
        minutesLabel = document.getElementById("minutes");
        secondsLabel = document.getElementById("seconds");
        my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
    }
    
    function stop_timer() {
      clearInterval(my_int);
    }
    
    
    </script>
    

    如下所示:

    【讨论】:

      【解决方案7】:

      @Cyber​​nate,我今天正在寻找相同的脚本,感谢您的输入。不过我对 jQuery 做了一点改动...

      function clock(){
          $('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
               var totalSeconds = 0;
              setInterval(setTime, 1000);
              function setTime()
              {
                  ++totalSeconds;
                  $('#clock > #seconds').html(pad(totalSeconds%60));
                  $('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
              }
              function pad(val)
              {
                  var valString = val + "";
                  if(valString.length < 2)
                  {
                      return "0" + valString;
                  }
                  else
                  {
                      return valString;
                  }
              }
      }
      $(document).ready(function(){
          clock();
          });
      

      css 部分:

      <style>
      #clock {
          padding: 10px;
          position:absolute;
          top: 0px;
          right: 0px;
          color: black;
      }
      </style>
      

      【讨论】:

        【解决方案8】:

        注意:在编写 jQuery 脚本之前始终包含 jQuery

        Step1: setInterval 函数每 1000ms (1s) 调用一次

        Stpe2: 在那个函数中。增加秒数

        第三步:检查条件

        <span id="count-up">0:00</span>
        <script>
        	  var min    = 0;
              var second = 00;
              var zeroPlaceholder = 0;
              var counterId = setInterval(function(){
                                countUp();
                              }, 1000);
        
              function countUp () {
                  second++;
                  if(second == 59){
                    second = 00;
                    min = min + 1;
                  }
                  if(second == 10){
                      zeroPlaceholder = '';
                  }else
                  if(second == 00){
                      zeroPlaceholder = 0;
                  }
        
                  document.getElementById("count-up").innerText = min+':'+zeroPlaceholder+second;
              }
        </script>

        【讨论】:

        • 为什么只在最后一行包含 jQuery?您可以通过执行 document.getElementById("#count-up").innerText(min+':'+zeroPlaceholder+second);
        【解决方案9】:

        查看这些解决方案:

        Compute elapsed time

        【讨论】:

          【解决方案10】:

          只是想投入我的 2 美分。我修改了 @Ajay Singh 的函数来处理倒计时和向上计数这是来自 jsfiddle 的片段。

          var countDown = Math.floor(Date.now() / 1000)
          runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
          var t = setInterval(function(){
            runClock(function(){
              console.log('done');
              clearInterval(t);
            },function(timeElapsed, timeRemaining){
              console.log( timeElapsed.seconds );
            }, countDown);
          }, 100);
          

          https://jsfiddle.net/3g5xvaxe/

          【讨论】:

          • 如果你想倒计时,你只需在将来创建 countDown 变量。所以它看起来像var countDown = Math.floor(Date.now() / 1000) + 15
          【解决方案11】:

          这是一个 React (Native) 版本:

          import React, { Component } from 'react';
          import {
              View,
              Text,
          } from 'react-native';
          
          export default class CountUp extends Component  {
          
              state = {
                  seconds: null,
              }
          
              get formatedTime() {
                  const { seconds } = this.state;
          
                  return [
                      pad(parseInt(seconds / 60)),
                      pad(seconds % 60),
                  ].join(':');
              }
          
              componentWillMount() {
                  this.setState({ seconds: 0 });
              }
          
              componentDidMount() {
                  this.timer = setInterval(
                      () => this.setState({
                          seconds: ++this.state.seconds
                      }),
                      1000
                  );
              }
          
              componentWillUnmount() {
                  clearInterval(this.timer);
              }
          
              render() {
                  return (
                      <View>
                          <Text>{this.formatedTime}</Text>
                      </View>
                  );
              }
          }
          
          function pad(num) {
              return num.toString().length > 1 ? num : `0${num}`;
          }
          

          【讨论】:

            【解决方案12】:

            这是一个使用.padStart()的:

            <!DOCTYPE html>
            <html lang='en'>
            <head>
              <meta charset='UTF-8' />
              <title>timer</title>
            </head>
            <body>
              <span id="minutes">00</span>:<span id="seconds">00</span>
            
              <script>
                const minutes = document.querySelector("#minutes")
                const seconds = document.querySelector("#seconds")
                let count = 0;
            
                const renderTimer = () => {
                  count += 1;
                  minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
                  seconds.innerHTML = (count % 60).toString().padStart(2, "0");
                }
            
                const timer = setInterval(renderTimer, 1000)
              </script>
            </body>
            </html>
            

            From MDN:

            padStart() 方法用另一个字符串(重复,如果需要)填充当前字符串,以使结果字符串达到给定长度。从当前字符串的开头(左侧)应用填充。

            【讨论】:

              【解决方案13】:

              这就是我构建 timerView 元素的方式,它不会因多次调用函数而混淆。

              function startOTPCounter(countDownDate){
               var countDownDate = '21/01/2022 16:56:26';//Change this date!!
                   var x = setInterval(function() {
                      var now = new Date().getTime();
                      var distance =  moment(countDownDate, 'DD/MM/YYYY hh:mm:ss').toDate().getTime() - now;
                      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
                      document.getElementById("timerView").innerHTML = minutes + "min " + seconds + "sn";
                      if (distance < 0) {
                          clearInterval(x);
                          // document.location.reload();
                          document.getElementById("timerView").innerHTML = "Expired!";
                      }
                  }, 1000);
              
              
                  if(window.preInterval != undefined){
                      clearInterval(window.preInterval);
                  }
                  window.preInterval = x;
                  
                   //if(sessionStorage.preInterval != undefined){
                   //   clearInterval(sessionStorage.preInterval);
                  //}
                  //sessionStorage.preInterval = x;
              }
              <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
              
              <html>
              <head>
              </head>
              <body>
              <div>
                <p style="color:red; font-size: 15px; text-align:center; "  id='timerView'></p>
                <input type="button" name="otpGonder" value="Send Again" class="buton    btn btn-default " onclick="startOTPCounter()" id="otpGonder">
              </div>
              </body>
              </html>

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-06-14
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多