Error message displayed: "The timer function encountered an issue as second_input is found to be null."

var idinterval;
var second_input_value = document.getElementById("Seconds");
var minute_input_value = document.getElementById("Minutes");
var second_val = second_input_value.value;
var minute_val = minute_input_value.value;

var total_time = parseInt(minute_val * 60) + parseInt(second_val);


function starter() {
  if (total_time > 0) {
    total_time = total_time - 1;
    document.getElementById("timing").innerHTML = Math.floor(total_time / 60) + ":" + total_time % 60;
    return;
  }
}

function start_the_clock() {
  setInterval(() => {
    starter();
  }, 1000);
}
::placeholder {
  font-size: 20px;
}

.ClockStart {
  color: white;
  width: 120px;
  height: 37px;
  padding: 6px;
  font-size: 15px;
  background-color: rgb(21, 27, 84);
  margin-top: 30px;
  margin-right: 5px;
}

.ClockStart:hover {
  background-color: #0000B9;
}

.ClockPause {
  color: white;
  width: 120px;
  height: 37px;
  padding: 6px;
  font-size: 15px;
  background-color: #767676;
  margin-top: 30px;
  margin-right: 5px;
}

.ClockPause:hover {
  background-color: #444444;
}

.ClockStop {
  color: white;
  width: 120px;
  height: 37px;
  padding: 6px;
  font-size: 15px;
  background-color: #B2B2B2;
  margin-top: 30px;
  margin-right: 5px
}

.ClockStop:hover {
  background-color: #303030;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="timer.css" />
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Timekeeper</title>
</head>

<body>
  <script src="timer.js" type="text/javascript"></script>
  <div style="margin-top:50px;margin-left:50px;">
    <h1 style="font-size: 60px; color: black;font-weight: bold;">Timekeeper</h1>
    <hr style="transform: rotate(90deg);margin-left:350px;width:200px ">
    <form id="timer_form">
      <label style="font-size: 30px; font-weight:100; font-style: italic; margin-bottom: 500px;width:5px">
Minutes   <input id="Minutes" value="0" placeholder="00"   style="font-size:20px;background-color:transparent;margin-left: 10px; color:black;height:30px; width: 200px;border-top: none;border-left: none;border-right: none;border-bottom: 1px solid black;" type="number" min="1 " max="2000000">
  </label>
      <br><br>
      <label style="font-size: 30px; font-weight:100; font-style: italic; margin-top: 100px ;">
    Seconds 
    <input id="Seconds" placeholder="00" value="0" style="font-size:20px;background-color:transparent;margin-left: 10px; color:black;height:30px; width: 200px;border-top: none;border-left: none;border-right: none;border-bottom: 1px solid black;" type="number" min="1 " max="2000000">
</label></form>
    <br>
    <button class="ClockStart" id="start" type="button" onclick="start_the_clock()">Start</button>

    <button class="ClockPause" id="pause" type="button" onclick="stop()">Pause</button>


    <button class="ClockStop" id="stop" type="button" onclick="reset()">Stop</button>
    <p id="timing" style="font-weight: 600;font-size:100px; position:relative; bottom:300px; left:500px;">00:00</p>
  </div>
</body>

</html>

Note: this is a basic function for keeping time where the user provides minutes and seconds as input in an HTML form ,this is the issue reported by the browser console after running the code

Could someone help me troubleshoot the problem?

Uncaught TypeError: second_input is null

Note: The error occurs only in the JavaScript portion of the code. When I tried changing the values of minute_input and second_input to integers, it worked fine

Answer №1

When your script tag is read, your javascript file is executed immediately, even before your Seconds input is defined

Here are 3 ways to address this issue:

  1. Move your javascript tag to the end of your html file
  2. Ensure your variables (those calling getElementById) are defined within your starter function
  3. Create a function that includes all your code and call it when the body is loaded using
    <body onload="myFunction()">

Answer №2

The reason for this issue is that the JavaScript code runs before the input HTML is displayed on the screen. I resolved this by relocating those variables to the specific functions where they are required.

Answer №3

Ensure that you organize your code properly by placing the JavaScript import after defining your elements. If the script runs before the element with id Seconds is created, it won't be able to find it.

To rectify this issue, consider moving the script import to the bottom of the HTML page or delaying the search for the element until the start button is clicked. You can achieve this by encapsulating all the code before the starter() function within the start_the_timer() function as demonstrated below. Just remember to ensure that both the start_the_timer and starter functions are accessing the same global total variable.

  var total = 0;

function starter() {
  if (total > 0) {
    total = total - 1;
    document.getElementById("timing").innerHTML = Math.floor(total / 60) + ":" + total % 60;
    return;
  }
}

function start_the_timer() {
  var idinterval;
  var second_input = document.getElementById("Seconds");
  var minute_input = document.getElementById("Minutes");
  var second_value = second_input.value;
  var minute_value = minute_input.value;

  total = parseInt(minute_value * 60) + parseInt(second_value);
  setInterval(() => {
    starter();
  }, 1000);
}
::placeholder {
  font-size: 20px;
}

.Starter {
  color: white;
  width: 120px;
  height: 37px;
  padding: 6px;
  font-size: 15px;
  background-color: rgb(21, 27, 84);
  margin-top: 30px;
  margin-right: 5px;
}

.Starter:hover {
  background-color: #0000B9;
}

.Pauser {
  color: white;
  width: 120px;
  height: 37px;
  padding: 6px;
  font-size: 15px;
  background-color: #767676;
  margin-top: 30px;
  margin-right: 5px;
}

.Pauser:hover {
  background-color: #444444;
}

.Stopper {
  color: white;
  width: 120px;
  height: 37px;
  padding: 6px;
  font-size: 15px;
  background-color: #B2B2B2;
  margin-top: 30px;
  margin-right: 5px
}

.Stopper:hover {
  background-color: #303030;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="timer.css" />
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clockworks</title>
</head>

<body>
  <script src="timer.js" type="text/javascript"></script>
  <div style="margin-top:50px;margin-left:50px;">
    <h1 style="font-size: 60px; color: black;font-weight: bold;">Clockworks</h1>
    <hr style="transform: rotate(90deg);margin-left:350px;width:200px ">
    <form id="timer_form">
      <label style="font-size: 30px; font-weight:100; font-style: italic; margin-bottom: 500px;width:5px">
        Minutes   <input id="Minutes" value="0" placeholder="00"   style="font-size:20px;background-color:transparent;margin-left: 10px; color:black;height:30px; width: 200px;border-top: none;border-left: none;border-right: none;border-bottom: 1px solid black;" type="number" min="1 " max="2000000">
      </label>
      <br><br>
      <label style="font-size: 30px; font-weight:100; font-style: italic; margin-top: 100px ;">
        Seconds 
        <input id="Seconds" placeholder="00" value="0" style="font-size:20px;background-color:transparent;margin-left: 10px; color:black;height:30px; width: 200px;border-top: none;border-left: none;border-right: none;border-bottom: 1px solid black;" type="number" min="1 " max="2000000">
      </label></form>
      <br>
      <button class="Starter" id="start" type="button" onclick="start_the_timer()">Start</button>

      <button class="Pauser" id="pause" type="button" onclick="stop()">Pause</button>


      <button class="Stopper" id="stop" type="button" onclick="reset()">Stop</button>
      <p id="timing" style="font-weight: 600;font-size:100px; position:relative; bottom:300px; left:500px;">00:00</p>
    </div>
  </body>

  </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a webpage that loads directly to a specific section of content

After searching online, I couldn't find the solution I was looking for. My goal is to have the visible part of the page load halfway down the actual page. This way, when users visit the site, they can immediately scroll up to see more content. I hope ...

Utilizing JQUERY to modify the 'top' attribute upon clicking

I am attempting to implement a vertical scroller using jQuery, but I'm encountering difficulties with my code. function scrolldown() { var newtop = $('.scroll-content').css('top') + '250'; $('.scroll ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

Angular Display of Scrolling Feature not Functioning Properly

After clicking on show5 and then goto5, everything functions as expected. However, when clicking on showngo5, it does not work as anticipated, despite the fact that the same methods are being called. What is causing showngo5 to not work in this plunker h ...

I am facing an issue with the Ionic Framework where the Javascript function for JWPlayer only works after the page is reloaded. Can anyone help

I'm currently troubleshooting the use of JWPlayer for streaming videos in an Ionic app. However, I've encountered a problem. The player only seems to load when I refresh the page, rather than when I navigate through the list of videos. Here is ...

What could be the reason for axios yielding [object Promise] rather than the actual data?

My issue involves a function that retrieves data from an API. However, when I integrate this function into an EJS template, it returns a promise instead of the desired data. Strangely, when I console.log the data, it displays the correct information. Assi ...

Implementing the array name property in a JSON object using ES5

I am currently working with a JSON object that has the following structure: {"Firstname":"john","Lastname":"doe"} My goal is to transform it into an array with a specific name 'abc': users: [{"Firstna ...

What is the most effective method for replacing a file with fs in node.js?

I am currently working on replacing an existing file with new content. To start, I check if the file exists using: fs.existsSync(path) If the file does not exist, I proceed to create and write to it using: fs.writeFileSync(path, string) The issue arise ...

What causes the size of text to change when I zoom in my browser?

As I work on my website, I am facing a challenge with maintaining consistent text size as the page scales. For example: p { width: 10%; height: 10%; background-color: rgb(0,0,0); top: 50%; left: 50%; position: fixed; color: rgb(255,255,25 ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...

Generate CANNON.RigidBody using either a THREE.Mesh or THREE.Geometry object

For my project, I am using a THREE.JSONLoader to create a THREE.Mesh object as shown below: // Creating a castle. loader.load('/Meshes/CastleTower.js', function(geometry, materials) { var tmp_material = new THREE.MeshLambertMaterial(); T ...

Create a CSS header with a fading background that extends horizontally to the left and right

I'm looking to create a header with a unique color transition effect - a left fade from light blue to blue, a center that is solid blue, and a right fade from blue to light blue. The header should span the full width of the page. Can anyone suggest th ...

Steps for aligning floating DIVs in the center of a parent DIV

Why is the text alignment not working as expected when I have three divs within a parent div that need to be center aligned? If you'd like to see the issue in action, check out this Demo fiddle <div class="container_alt"> <div class= ...

JavaScript and HTML have encountered an Uncaught TypeError: The property 'addEventListener' cannot be read because it is null

Having an issue here. Whenever I try to play sound from an image, I encounter an error. Uncaught TypeError: Cannot read property 'addEventListener' of null Here is my HTML code: <html> <head> <title>Music</title> < ...

Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with: { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name": "test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "fr ...

I am looking to halt the AJAX requests within an asynchronous function after reaching a limit of 10 requests

I've been working on an async function that sends AJAX requests based on the previous response. The function is functioning properly, but it's sending multiple requests in quick succession. I need to implement a 5-second interval between each req ...

Planning and organization of a Node.js/Express project

Having a background in MVC programming with frameworks like Laravel, CodeIgniter, and Django, I have now transitioned to working on larger projects in Node.js. However, I am struggling to find a suitable way to structure my project effectively... After so ...

After the execution of the script by V8, which phase will be initiated first?

Scenario // test.js setTimeout(() => console.log('hello'), 0) setImmediate(() => console.log('world')) Simply execute node test.js using node v12.12.12 on an Intel MacBook Pro. The output may vary: hello world Sometimes it is: ...

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

What is the most optimal method for exchanging data between a node.js server and a C# client?

I have set up a server in node.js with socket.io for HTML5 clients. Additionally, I have a specific client written in C# to operate on Microsoft's PixelSense device. Originally, I intended to utilize C# socket.io implementations, but unfortunately, I ...