从头开始​​创建秒表

从头开始​​创建秒表

本文介绍了用 JavaScript 从头开始​​创建秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

通过为毫秒、秒和分钟创建变量,我想做一个小秒表项目.我拥有的按钮的 onClick 用于 theTimer():

By creating variables for milliseconds, seconds, and minutes, I wanted to make a little stopwatch project. The onClick for the button I have is for theTimer():

var milli = 0;
    var seconds = 0;
    var minutes = 0;
    var onOff = 0;

    var txtMilli = document.getElementById("txtMilli");
    var txtSeconds = document.getElementById("txtSeconds");
    var txtMinutes = document.getElementById("txtMinutes");

    function theTimer()
    {
        if (onOff == 0) {
            onOff = 1;
            timer = setInterval("startCounting()",1);
        }
        if (onOff == 1) {
            onOff == 0;
            clearInterval(timer);
        }
    }

    function startCounting()
    {
        if (milli >999)
        {
          milli = 0; if (seconds <60) {seconds +=1}
        }
        else
        {
          milli +=1;
        }
        if (seconds >59)
        {
          seconds = 0; minutes += 1;
        }
        if (milli > 10)
        {
          txtMilli.innerHTML = "0" + milli;
        }
        if (milli < 10)
        {
          txtMilli.innerHTML = "" + milli;
        }
    }

控制台中什么都没有显示,问题是 DIV 在运行时永远不会从 0 改变.

Nothing shows up in the console, the problem is that the DIVs never change from 0 when running it.

推荐答案

我设法修复了您的代码,如下所示:

I managed to fix your code like so:

var milli = 0;
var seconds = 0;
var minutes = 0;
var onOff = 0;

var txtMilli = document.getElementById("txtMilli");
var txtSeconds = document.getElementById("txtSeconds");
var txtMinutes = document.getElementById("txtMinutes");

function startCounting(){
    if (milli >999) { milli = 0; if (seconds <60) {seconds +=1} }
    else {milli +=1;}
    if (seconds >59) {seconds = 0; minutes += 1;}

    if (milli > 10) {txtMilli.innerHTML = "0" + milli;}
    if (milli < 10) {txtMilli.innerHTML = "" + milli;}
}

function theTimer(){
    if (onOff == 0) {
        onOff = 1;
        timer = setInterval(startCounting, 1);
    } else if (onOff == 1) {
        onOff = 0;
        clearInterval(timer);
    }
}

myButton.onclick = theTimer;

theTimer 中存在一个错误,您将 onOff 设置为 1,然后立即检查它是否为 1 并将其设置回 0.我通过使用 else if 解决了这个问题.

There was a bug inside theTimer where you'd set onOff to 1, then immediately check to see if it was 1 and set it back to 0. I fixed this by using else if.

我还将 onOff == 0(这是一个比较)更改为 onOff = 0(这是一个赋值).

I also changed onOff == 0 (which is a comparison) to onOff = 0 (which is an assignment).

工作 JSFiddle:https://jsfiddle.net/k83tvfhc/

Working JSFiddle: https://jsfiddle.net/k83tvfhc/

这篇关于用 JavaScript 从头开始​​创建秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:01