Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearInterval() not working on clock timer with JavaScript

I am very new to JavaScript and programming in general. I am currently in a little pickle with some code that I am playing around with, and I am wondering if anyone can give me some advice.

Background:

The code I am working with is rather simple; There is a clock with the current time running on setInterval to update by the second.

Below the clock there is a button that reads “Stop,” and when pressed, it will clear the Interval and the button will then read “Start.” If the button, which reads “Start” is pressed again, it will continue the clock timer in its current time. So basically this one button toggles the interval of the clock, and depending on which state it is, the button will read “Start” or “Stop.”

W3Schools: JS Timing is where I am originally referencing when creating the code I am working with. This is where I am learning about how setInterval and clearInterval works. I also took some of the code in the examples and adjusted it so I can try to make the clock timer toggle off and on.

Code:

var clock09 = window.setInterval(myTimer09, 1000);

function myTimer09() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("req09").innerHTML =
    "<h1>" + t + "</h1>";
}

function toggle10() {
  var button = document.getElementById("button10").innerHTML;
  if (button == "Stop") {
    window.clearInterval(clock09);
    document.getElementById("button10").innerHTML = "Start";
  } else {
    clock09 = window.setInterval(myTimer09, 1000);

    document.getElementById("button10").innerHTML = "Stop";
  }
}
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>

https://jsfiddle.net/dtc84d78/

Problem:

So my problem with the code is that the button toggles from a “Stop” button to a “Start” button, but the clearInterval is not applying to the Variable with the setInterval.

I have googled similar problems in SO, such as this one, and I followed their advice, and still nothing. After hours of trying to figure out, I decided to just copy and paste some example from W3Schools straight to jsFiddle, and that didn’t even work (included in jsfiddle link)?

I am really just going crazy on why anything with clearInterval() is not working with me? Could it be my computer, browser or anything else? I am coming to SO as my last resource, so if anyone can give me some guidance to this problem, I will name my first child after you.

Thank you in advance.

Extra Info: I am currently working on a Mac desktop, using Komodo to write the code, and I am using Google Chrome to preview the code.

UPDATE:

I mentioned this in the comments, but coming in the code was in an external .js file. The .js file was then linked in between the head tags, and right before the end body tag.

<head>
  <meta charset="utf-8" />
  <title>Program</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/program-05.css">
  <script type="text/javascript" src="scripts/program-05.js">
    /* <![CDATA[ */
    /* ]]> */
  </script>
</head>

<body onload="checkCookies(); setTimeout(function() { func11() }, 5000);">

  . . . code for stuff

  . . . code for clock timer

  . . . code for other stuff

  <script type="text/javascript" src="scripts/program-05.js">
    /* <![CDATA[ */
    /* ]]> */
  </script>
</body>

After @Matz mentioned to stick the clock timer js code in the head section, the code worked great! This is what it looks like so far in the head section.

<head>
  <meta charset="utf-8" />
  <title>Program</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/program-05.css">
  <script type="text/javascript" src="scripts/program-05.js">
    /* <![CDATA[ */
    /* ]]> */
  </script>
  <script>
    ///*
    var clock09 = window.setInterval(myTimer09, 1000);

    function myTimer09() {
      var d = new Date();
      var t = d.toLocaleTimeString();
      document.getElementById("req09").innerHTML =
        "<h1>" + t + "</h1>";
    }

    function toggle10() {
        var button = document.getElementById("button10").innerHTML;
        if (button == "Stop") {
          window.clearInterval(clock09);
          document.getElementById("button10").innerHTML = "Start";
        } else {
          clock09 = window.setInterval(myTimer09, 1000);

          document.getElementById("button10").innerHTML = "Stop";
        }
      }
      //*/
  </script>
</head>

Though this works great, I now want to figure out as to why the clock timer js code works when it is directly in the head section as compared to keeping it in the external .js file (with the external file being linked in the doc)? What can I do to make it work within the external file?

like image 382
unavailableUsername Avatar asked Oct 30 '22 18:10

unavailableUsername


1 Answers

Problem:

This is because the default Load Type is set to onLoad which is wrapping your javascript code in window.onload = function() {} hence the scope of your function was getting limited to the onload function and it wasn't available outside:

enter image description here

Solution:

Click on the Javascript setting in the Javascript section of the Fiddle, change it to No wrap - in body and it will work since this will now place your Javascript code in the body tag.

Additional Note:

Your code is also working via StackOverflow snippet:

/*My Problem*/
var clock09 = window.setInterval(myTimer09, 1000);

function myTimer09() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("req09").innerHTML =
    "<h1>" + t + "</h1>";
}

function toggle10() {
  var button = document.getElementById("button10").innerHTML;
  if (button == "Stop") {
    window.clearInterval(clock09);
    document.getElementById("button10").innerHTML = "Start";
  } else {
    clock09 = window.setInterval(myTimer09, 1000);

    document.getElementById("button10").innerHTML = "Stop";
  }
}

/*W3S Problem*/
var myVar = setInterval(myTimer, 1000);

function myTimer() {
  var d = new Date();
  document.getElementById("demo").innerHTML =
    d.toLocaleTimeString();
}
<!-- My Problem -->
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>

<hr>
<hr>
<!-- W3S Problem -->
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>

Recommendation

Separation of concerns

I'll recommend you moving your javascript code in the external file and later include them in your HTML using script tag. So for example, you moved your code in app.js then include that in your HTML as:

<!-- make sure the path here is relative to the current HTML -->
<script src="./app.js"></script>
like image 82
Shashank Agrawal Avatar answered Nov 12 '22 09:11

Shashank Agrawal