如何使用RunTime函数更新时钟?

时间:2019-12-28 03:50:21

标签: javascript html algorithm web-applications

我正在研究一个小型数字时钟项目,该项目应该通过使用电源按钮打开时钟并显示当前时间来模拟真实时钟,并关闭时钟电源并使显示器呈​​现为空的。这就是该项目应该执行的操作,但是现在它正在执行该操作。第一次单击该按钮时,它会将当前时间作为内部文本呈现到显示中,但不会随着我使用的setInterval函数进行更新。只有控制台会打印当前时间和更新。我可以为我的代码获取一些帮助吗?如果有不清楚的地方,我对项目有一些说明,请多谢。我想弄清楚为什么我要关闭电源时时钟没有关闭,为什么我的时间也没有像我想要的那样在显示器上更新。我下面有一些代码来说明我尝试编写的内容。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        #digital-clock {
            border: 2px solid black;
            height: 200px;
            position: relative;
            width: 400px;
        }
        #display {
            border : 2px solid black;
            border-radius: 9px;
            font-size: 40px;
            height: 55px;
            line-height: 55px;
            position: absolute;
            top: 10px;
            left: 15px;
            text-align: center;
            width: 250px;
        }

        #button {
            border: 2px solid black;
            border-radius: 50%;
            font-size: 16px;
            height: 55px;
            line-height: 55px;
            position: absolute;
            top: 10px;
            left: 305px;
            text-align: center;
            width: 55px;
        }


    </style>
</head>
<body>

    <div id="display"></div>
    <div id="button">OFF</div>
</body>
<script language="javascript" type"text/javascript" src="digtalclock.js"></script>
</html>

var c_d = document.getElementById("display");
var btn = document.getElementById("button");
console.log(btn)
console.log(c_d);

function setTime() {
    var d = new Date();//current date and time. 
    var h = d.getHours();//the current hours.
    var m = d.getMinutes();//the current minutes.
    var s = d.getSeconds();//the current seconds.
    var ct = `${h}:${m}:${s}`; // a var called ct short for clocktime which does the same as h +":"+ m +":"+s
    console.log(ct);//ct logs current time and updates occordingly when page is refreshed.
    runTime(ct);// callBack for runTime with ct as parament value. 
}
function runTime(x) {
    var t = x;//var ct passed in as parameter from setTime function and stored as data into variable t in runTime().
    console.log(t);//t is still console logging ct the variable data.
    var n = 0;//used for tracking clicks 
    console.log(n);
    btn.addEventListener("click",function(e) {//click toggle function. 
        n += 1;// increments by 1 everytiime click executes. 
        var c = setInterval(setTime,1000);//a setInterval statement which is supposed make time tick but only on the console. not on display like i want to. 
        console.log(n);
        const s = ["ON ","OFF"," ",];
        //*************NOTES REGARDING THE IF STATEMENT*****************
        //**************************************************************
        /*odd and even numbers are used to keep track of the click event.
        the if statement is used to detect even numbers. Inside the body 
        i used the constant string variable s which has 3 strings indexed
        and combine that with click button event to create a toggle effect 
        indicating when the power is on the else statement is read because 
        when you click the button the first number to appear is odd, and 
        since n increments by one the following number is 2 and even. So the 
        if statements states if n is even when you click the button the text 
        inside is changed by grabbing one of the 3 indexed items of const s array. 
        the power button excutes as off and the dispay is supposed to go blank 
        by using an empty string that is indexed inside the cost s variable. */
        if(n % 2 === 0)  {
            console.log("Even Num");
            btn.innerHTML = s[1];
            c_d.innerHTML = s[2];
            c = clearInterval(c);
        } 
        //**************NOTES REGARDING THE ELSE STATEMENT*******************
        /*The purpose of the else statment is. Since we are treating the project
        as if it were a real life clock with on and off power buttons. when n and btn 
        interact for the first time it console.logs 1 meaning our first odd number is 
        created. and n is incremented by one. since n starts with a value of 0. its logical to 
        say that if you click the button 1 is added to n everytime. furthermore, i use n to keep
        track of the clicks . Since were powering on the clock the inner text of the 
        button will use cost s variale and and the first indexed item to idicate the power 
        is on. for the clock display or the section where you see time apear at i used the 
        c_d var name short for clock_display and passed it a method of innerHTML = to t because
        i thought i finally invoked the set interval function but time is not updating. it 
        is only displaying current time at the point of click as innerHTML. while it updates on the console. 
        nothing updates on the display.*/
        else{
            console.log("odd num");
            btn.innerHTML = s[0];
            c_d.innerHTML = t;
        }
    });
}
setTime();

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>test</title>

</head>
<body>
  <div>Time <span id="time">00:00:00</span> </div>
  <div><button id="btn">Power off</button></div>
  <div><button id="on">Power On</button></div>

  <script>

      var btn = document.getElementById("btn");
      var on = document.getElementById("on");
      var timestamp = new Date();

      var interval = 1;
      var flag = 0;
      var mytimer = setInterval(function () {
          timestamp = new Date(timestamp.getTime() + interval * 1000);
          btn.addEventListener("click",function(e) {
            flag = 1
          })
          on.addEventListener("click",function(e) {
            flag = 0
          })
          if(flag == 0)
          document.getElementById('time').innerHTML =  timestamp.getHours() + 'h:' + timestamp.getMinutes() + 'm:' + timestamp.getSeconds() + 's';
          else
          document.getElementById('time').innerHTML = '0h: 0m: 0s';
      }, Math.abs(interval) * 1000);



  </script>
</body>
</html>

尝试一下。这里有两个按钮开机和关机