5

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?

Community
  • 1
  • 1
  • You can fix your fiddle simply by changing `function toggle10() {` to `document.toggle10 = function() {` – Matt Way Oct 09 '16 at 05:15
  • I just realized the code works in the SO snippet! Unfortunately, the code that I am working with will need to be in an index.html file that I am working on, which is also where I do not get the results that I want with this code. I’m currently trying to see if any of the suggestions given will solve the problem. Note: all of the javascript is in an external file .js file that is linked in the HEAD and right before the BODY tag. I do not have any console errors as well. – unavailableUsername Oct 09 '16 at 06:51
  • So far out of all the suggestions, putting the javascript code for this problem in between the head tags is working for me! Right now my external .js file is linked followed by the js code for the clock timer. – unavailableUsername Oct 09 '16 at 07:02
  • Looks like this post is getting bigger and your original problem of js not being called inline is solved isn't it? As for external JS file problem, that would be a different question, consider posting it separately. – Shashank Agrawal Oct 09 '16 at 08:16
  • I think I will just go ahead and post within HTML file. I will just google a bit more about the external JS file problem before I post anything else. Thank you everyone, for all the suggestions! – unavailableUsername Oct 09 '16 at 08:41

4 Answers4

2

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>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • 1
    I am glad you and @spen brought this up, because I now know why it didn't work on fiddle. My attempt to duplicate this is pasting the script in between the head tags. Any suggestions on how to make the code work using the code in an external .js file? Worst case scenario I will just leave the script in between head tags. P.s. seriously love the use of graphics! Made me follow along easier. – unavailableUsername Oct 09 '16 at 06:59
  • Coming in, all of the js code was in an external file. The file was linked to the html doc in between the head tags, as well as before the end body tag. It looks like this: . Unfortunately, this method does not work. Currently the external file is linked, because I have other things there, but the js code for the timer clock is in between script tags in the head section following the external file. – unavailableUsername Oct 09 '16 at 07:34
  • Can you provide fiddle reproducing this issue – Shashank Agrawal Oct 09 '16 at 07:37
  • I have edited my post up top since I cant include how my head section looked and looks currently in jsfiddle. – unavailableUsername Oct 09 '16 at 08:04
0

You are declaring a new date variable in the myTimer09 function, so every time it is called, it shows the current time. You should declare the time outside the function, then pass it to the function. When you stop the timer, you should save the time value so that you can restart with that value.

genestd
  • 384
  • 3
  • 16
  • Tried it but it just showed the current time, and did not update the time of 1 second intervals. Also what I need is when the button “start” is pressed, the clock timer will continue, but with the current time, not the value it stopped at. So I don’t think this would work. Thank you for the suggestion! – unavailableUsername Oct 09 '16 at 06:54
0

One way to fix the timer starting and stopping is to move the javascript in between the HEAD tags so the functions are declared by the time the html loads. I made this work:

<html>
  <head>
    <title>Stuff</title>

    <script >

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

      .... your code

   </script>

  </head>
  <body>
    <span class="center" id="req09"></span>
    <button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>

  </body>
</html>
Matz
  • 371
  • 1
  • 2
  • 5
  • I put the js code in between head tags as @Matz mentioned. Result: It freaking works! I am glad this works, but I need to find a solution where I don’t need to include it in the head tags, and I can leave it in the external file. Worst case scenario, this is what I will go with. Any suggestions? – unavailableUsername Oct 09 '16 at 06:53
  • Just drop the javascript into a file.. say timerstuff.js and change the script tag to: . It is still in the head tags but code is in a separate file. – Matz Oct 09 '16 at 06:56
0

This seems to be an issue with JSFiddle.

The onclick handler is looking for window.toggle10 which isn't actually defined (check for the error in the console). It seems that this is something others have seen with JSFiddle

I've C&Ped your code in to a JSbin and it works as described!

Community
  • 1
  • 1
Spen
  • 512
  • 4
  • 7
  • now I see why the js didn’t work in fiddle. My attempt to duplicate this is pasting the script in between the head tags. Any suggestions on how to make the code work using the code in an external .js file? Worst case scenario I will just leave the script in between head tags. – unavailableUsername Oct 09 '16 at 06:56