在javascript中普通计数计时器

时间:2011-04-01 18:53:38

标签: javascript

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

13 个答案:

答案 0 :(得分:67)

检查一下:

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;
  }
}
<label id="minutes">00</label>:<label id="seconds">00</label>

答案 1 :(得分:39)

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>

Pure 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);
<span id="minutes"></span>:<span id="seconds"></span>

更新

answer显示如何填充。

使用clearInterval MDN

停止setInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );

Fiddle

答案 2 :(得分: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;
}

答案 3 :(得分:3)

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

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 startTime() {
    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(startTime, 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;
}

startTime();

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

答案 4 :(得分:3)

摆弄Bakudan的代码和stackoverflow中的其他代码,将所有内容整合在一起。对不起,它使用jquery,但使用起来非常简单。有一个暂停选项,然后恢复它。

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

在这里弄清楚:https://jsfiddle.net/wizajay/rro5pna3/

<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">


var Clock = {
totalSeconds: 0,

start: function () {
    var self = this;
    function pad(val) { return val > 9 ? val : "0" + val; }
    this.interval = setInterval(function () {
    self.totalSeconds += 1;


    $("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
    $("#sec").text(pad(parseInt(self.totalSeconds % 60)));
  }, 1000);
},

reset: function () {
Clock.totalSeconds = null; 
clearInterval(this.interval);
$("#min").text("00");
$("#sec").text("00");
},

pause: function () {
clearInterval(this.interval);
delete this.interval;
},

resume: function () {
if (!this.interval) this.start();
},

restart: function () {
 this.reset();
 Clock.start();
}
};


$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
$('#resetButton').click(function () { Clock.reset(); });
$('#restartButton').click(function () { Clock.restart(); });

答案 5 :(得分:1)

@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>

答案 6 :(得分:1)

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

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

Stpe2:在该功能中。增加秒数

第3步:检查条件

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 7 :(得分: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;
  }
}
<label id="minutes">00</label>:<label id="seconds">00</label>

答案 8 :(得分:0)

查看以下解决方案:

Compute elapsed time

答案 9 :(得分:0)

只想把我的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/

答案 10 :(得分:0)

这是一个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}`;
}

答案 11 :(得分:0)

从@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>

如下所示:

enter image description here

答案 12 :(得分:0)

这是一个使用.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()方法用另一个字符串填充当前字符串(如果需要,重复),以便生成的字符串达到给定的长度。填充从当前字符串的开头(左侧)开始应用。