【问题标题】:How do I display millisecond in my stopwatch?如何在秒表中显示毫秒?
【发布时间】:2014-12-07 10:08:18
【问题描述】:

我正在使用 Javascript 实现秒表。我有基本的 html 文档设置和一个名为 stopwatch.js 的 javascript 文件,其中包含以下代码。我利用setInterval 函数每1 秒(1000 毫秒)执行一次clockRunning 函数。这使我可以控制秒、分钟和小时以相应地增加它们,但我在将毫秒插入秒表时遇到了困难。我应该如何将毫秒从 0 增加到 1000 然后重置为零?

我尝试减少每 1ms 调用一次 setInterval 函数的间隔时间,然后将 millisecond 变量设置为 time%1000,其中每次调用函数时,time 变量都会增加 1。但它并没有给出我想要的结果。 millisecond 似乎增长得太慢了。

var running = 0
var time = 0;
var hour = 0;
var min = 0;
var sec = 0;
var millisec = 0;


function start(){
	started = window.setInterval(clockRunning, 1000);	
}

function stop(){
	window.clearInterval(started);
}

function clockRunning(){
	time++;
	sec++;
	if (sec == 60){
		min += 1;
		sec = 0;
	if (min == 60){
		hour += 1;
		min = 0;
	}
	
	
	}

	document.getElementById("display-area").innerHTML = (hour ? (hour > 9 ? hour : "0" + hour) : "00") 
	+ ":" + (min ? (min > 9 ? min : "0" + min) : "00") + ":" + (sec > 9 ? sec : "0" 
		+ sec);
};
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Stopwatch</title>
        <script src="stopwatch.js"></script>
        <style>
            #display-area { font-size: 20pt; }
        </style>

    </head>
    <body>
        <div>
            <output id="display-area">00:00:00.000</output>
        </div>
        <div>
            <button id="toggle-button" onClick="start()">Start</button>
            <button id="toggle-button" onClick="stop()">Stop</button>
            <button id="reset-button">Reset</button>
        </div>
    </body>
</html>

【问题讨论】:

标签: javascript stopwatch


【解决方案1】:

您应该记录开始时间,然后使用 Date 从当前时间中减去该时间:

var timeBegan = null
    , timeStopped = null
    , stoppedDuration = 0
    , started = null;

function start() {
    if (timeBegan === null) {
        timeBegan = new Date();
    }

    if (timeStopped !== null) {
        stoppedDuration += (new Date() - timeStopped);
    }
    console.log(stoppedDuration);

    started = setInterval(clockRunning, 10);	
}

function stop() {
    timeStopped = new Date();
    clearInterval(started);
}
 
function reset() {
    clearInterval(started);
    stoppedDuration = 0;
    timeBegan = null;
    timeStopped = null;
    document.getElementById("display-area").innerHTML = "00:00:00.000";
}

function clockRunning(){
    var currentTime = new Date()
        , timeElapsed = new Date(currentTime - timeBegan - stoppedDuration)
        , hour = timeElapsed.getUTCHours()
        , min = timeElapsed.getUTCMinutes()
        , sec = timeElapsed.getUTCSeconds()
        , ms = timeElapsed.getUTCMilliseconds();

    document.getElementById("display-area").innerHTML = 
        (hour > 9 ? hour : "0" + hour) + ":" + 
        (min > 9 ? min : "0" + min) + ":" + 
        (sec > 9 ? sec : "0" + sec) + "." + 
        (ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Stopwatch</title>
        <style>
            #display-area { font-size: 20pt; }
        </style>

    </head>
    <body>
        <div>
            <output id="display-area">00:00:00.000</output>
        </div>
        <div>
            <button id="toggle-button" onClick="start()">Start</button>
            <button id="toggle-button" onClick="stop()">Stop</button>
            <button id="reset-button" onClick="reset()">Reset</button>
        </div>
    </body>
</html>

您之前看到毫秒“滞后”的原因是 setInterval 在您指定时不触发准确而臭名昭著。您可以使用上述策略解决此问题。

更新:您可以跟踪计时器在两次重置之间“暂停”了多长时间。更新了我的答案以适应这一点。

【讨论】:

  • 这里有一个问题。即使clearInterval 停止计时,计数似乎也没有停止。我点击stop,几秒钟后,再次点击start,这一次,时间已经过去了几秒钟。我的意思是它不会从停止时重新启动/恢复。知道如何实现这个resume 函数吗?
  • 圣烟!这正在工作:) 感谢您的帮助!
【解决方案2】:

完整代码在这里

  $(document).ready(function () {
    var milliseconds;
    var hours;
    var minutes;
    var seconds;
    var interval;
    var count = 0;
    var lap;
    var i = 0;
    $(".heading").slideDown("slow"); //slide down heading countdown.

    // click function to start timer
    $(".start").click(function () {
      $(".start").hide();
      $(".pause").show(100);    // show pause button
      $("#end").text("Stopwatch Started"); // change text.
      interval = setInterval(newtimer, 10); // run the countdown interval of 1000 millisecond
    });

    function newtimer() {
      hours = parseInt(count * 10 / 1000 / 60 / 60);// calculate hours
      minutes = parseInt(count * 10 / 1000 / 60);  // calculate minutes
      seconds = parseInt((count * 10 / 1000)%60);// calculate seconds
      milliseconds = parseInt((count*10) % 1000); // calculate milliseconds
      /* display digits in clock manner */
      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;
      count++; // increment in count.
      $(".seconds").text(hours + " : " + minutes + " : " + seconds + " : " + milliseconds);
    }

    /* click function to pause timer*/
    $(".pause").click(function () {
      $(".start").hide();      //hide start button
      $(".restart").hide();  //hide restart button
      $(".pause").hide();
      $(".resume").show();  // show resume button.
      $("#end").text("Stopwatch Paused");
      clearInterval(interval);  //clear interval will stop the count.
      i = i + 1;
      lap = " " + hours + " : " + minutes + " : " + seconds + " : " + milliseconds;
      $(".lap").append('<p>' + 'Time Lap' + "-" + i + lap + '</p>'); // add p tag in div and count no. of laps.
    });

    /* click function to resume the countdown */
    $(".resume").click(function () {
      $("#end").text("Stopwatch Resumed");// change end text.
      $(".pause").show();
      $(".resume").hide();
      interval = setInterval(newtimer, 10);// interval to function new timer. count will remain same where paused.
    });

    /* click function to stop stopwatch */
    $(".stop").click(function () {
      $("#end").text("Stopwatch Stopped");
      $(".restart").show();   //show restart button
      $(".resume").hide();    // hide resume button
      $(".start").hide();// hide start button
      $(".pause").hide();
      $(".lap p").remove();   // remove laps.
      clearInterval(interval);
    });

    /*click function to restart stopwatch*/
    $(".restart").click(function () {
      $("#end").text("Stopwatch Restarted");// change end text.
      $(".restart").hide();
      $(".pause").show();
      count = 0;      // count reset  to zero
      interval = setInterval(newtimer, 10); //time interval to function new timer
    });
    /* click function on class reset to reset the countdown */
    $(".reset").click(function () {
      $(".seconds").text("00 : 00 : 00 : 00"); // set display to initial value.
      $(".resume").hide();   // hide resume button
      $(".start").show();   // show start button
      $(".pause").hide();   // hide pause button
      $(".restart").hide();  // hide restart button
      $("#end").text(" ");   // change end text
      $(".lap p").remove();  // remove p tag from div
      clearInterval(interval);  // clear interval
      count = 0;               // reset count to initial value.
    });
  })

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>stopwatch</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
           integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script></head>
<body style="font-family: cursive;">
<div class="container-fluid clearfix" style="padding:100px; background-color:lightgrey;">
    <div style="width:25%; float:left"><img src="./bn.jpg" alt="stopwatch" style="width:100%"></div>
    <div class="heading" style="color:#165caa;display:none;margin-left: 365px;font-size: 84px">STOPWATCH</div>
    <div class="seconds" style="font-size: 46px;text-align:center;margin-top:30px "> 00 : 00 : 00 : 00</div>
    <div style="text-align:center;">
        <button class="start mt-3 px-4 btn btn-success">START</button>
        <button class="restart mt-3 px-4 btn btn-success" style="display:none">RESTART</button>
        <button class="resume mt-3 px-4 btn btn-success" style="display:none">RESUME</button>
        <button class="pause mt-3 px-4 btn btn-warning" style="display: none">PAUSE</button>
        <button class="stop  mt-3 px-4 btn btn-dark">STOP</button>
        <button class="reset mt-3 px-4 btn btn-danger">RESET</button>
    </div>
    <p id="end" style="font-size:32px ;margin-top:30px;text-align:center"></p>
    <div class="lap" style="text-align: center; font-size:16px;font-family: monospace;"></div>

</div>
</body>
</html>

【讨论】:

    【解决方案3】:

    错误修复!!!

    我注意到,如果您使用上面的代码多次点击 Start,Start、Stop、Reset 将不起作用。我可以通过调整启动功能来解决这个问题!

    function start() {
    
    if (timeBegan === null) {
        timeBegan = new Date();
    }else {
        clearInterval(started);
    };
    
    if (timeStopped !== null) {
        stoppedDuration += (new Date() - timeStopped);
    };
    
    if (stoppedDuration < 1000){
        console.log(stoppedDuration+' ms');
    };
    
    if (stoppedDuration > 1000){
        console.log(stoppedDuration/1000+' seconds');
    };
    
    started = setInterval(clockRunning, 10);
    
    return stoppedDuration  }
    

    【讨论】:

      猜你喜欢
      • 2013-03-17
      • 2011-03-06
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      相关资源
      最近更新 更多