在javascript中普通计数计时器

Mar*_*ark 44 javascript

我在javascript中寻找一个简单的计数器.我找到的所有剧本都"全都在唱歌".我只想要一个免费的jQuery,最小的大惊小怪计时器,以分钟和秒显示.谢谢.

Cha*_*ndu 73

检查一下:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)
<label id="minutes">00</label>:<label id="seconds">00</label>
Run Code Online (Sandbox Code Playgroud)

  • 我不推荐这种方法,因为它可能会导致执行延迟导致错误的值.更好的方法是基于系统时间的计时器. (15认同)

Bak*_*dan 40

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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="minutes"></span>:<span id="seconds"></span>
Run Code Online (Sandbox Code Playgroud)

纯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);
Run Code Online (Sandbox Code Playgroud)
<span id="minutes"></span>:<span id="seconds"></span>
Run Code Online (Sandbox Code Playgroud)

更新:

这个答案显示了如何填充.

停止setInterval的MDN与clearInterval实现MDN

var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
Run Code Online (Sandbox Code Playgroud)

小提琴


小智 15

以下代码用作计数计时器.这是纯粹的JavaScript代码hour:minute:second.它还有一个STOP按钮:

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

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);

   document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
}
Run Code Online (Sandbox Code Playgroud)


ort*_*omy 15

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

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();
Run Code Online (Sandbox Code Playgroud)

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

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

Aja*_*ngh 6

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

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

更新 #2:编辑出以前使用的纯 JS 的 JQuery 代码并添加为代码片段。

对于以前基于 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(); });
Run Code Online (Sandbox Code Playgroud)
<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">
Run Code Online (Sandbox Code Playgroud)


Cyb*_*tic 5

从 @Chandu 扩展,添加了一些 UI:

<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>
Run Code Online (Sandbox Code Playgroud)

看起来如下:

在此输入图像描述