I can't seem to get my clock to function properly. What could be causing InnerHTML to not update?

Hi there! I've been dabbling in learning JavaScript lately and thought it would be cool to create a basic clock. However, I'm running into an issue where I can't seem to update the values for the hours, minutes, and seconds. I tried using .innerHTML along with setInterval but it's not working as expected. Even in Chrome's inspector, it looks like the data is changing, but nothing happens on the display. Any suggestions or ideas on what might be going wrong?

<!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">
    <link rel="stylesheet" href="../css/style-clock.css">
    <title>Clock</title>
</head>
<body>
    <div class="container">
        <div class="clock">
            <span id="hours"></span>
            <span id="mins"></span>
            <span id="secs"></span>
        </div>
    </div>
<script src='../js/app-clock.js'></script>    
</body>
</html>

JS:

const time = new Date();

function currentTime(){
    var hour = time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    document.getElementById("hours").innerHTML = hour;
    document.getElementById("mins").innerHTML = minute;
    document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);

Answer №1

You were almost there! By defining the time variable outside of the interval function, it only gets assigned once. To fix this, simply move the time assignment inside the currentTime() function like so:

function currentTime() {
  const time = new Date();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  document.getElementById("hours").innerHTML = hour;
  document.getElementById("mins").innerHTML = minute;
  document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime, 500);
<div class="container">
  <div class="clock">
    <span id="hours"></span>
    <span id="mins"></span>
    <span id="secs"></span>
  </div>
</div>

Answer №2

You've slowed down outside the intervals function call.

Check out this CodePen Example

HTML

<!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>
    <link rel="stylesheet" href="../css/style-clock.css">
    <title>Clock</title>
</head>
<body>
    <div class="container">
        <div class="clock">
            <span id="hours"></span>
            <span id="mins"></span>
            <span id="secs"></span>
        </div>
    </div>
<script src='../js/app-clock.js'></script>    
</body>
</html>

JS

setInterval(function(){
  const time = new Date();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  document.getElementById("hours").innerHTML = hour;
  document.getElementById("mins").innerHTML = minute;
  document.getElementById("secs").innerHTML = second;
}, 500);

Answer №3

The issue lies in the placement of the time constant.

Essentially, the output generated by Date() is assigned to the constant time at the start of the script and the function currentTime() continuously updates these same values. As a result, even though the values are being updated, they remain unchanged visually leading to confusion.

Resolution: To rectify this, you must update the value of the time constant every time you wish to refresh the innerHTML. Simply implement the following adjustment:

JS:

function currentTime(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);

Answer №4

To ensure the time displayed updates correctly, it is best to move the "new Date()" line inside the function so that each interval sets the time to the current time.

function currentTime(){
  const time = new Date();
  var h = time.getHours();
  var m = time.getMinutes();
  var s = time.getSeconds();
  document.getElementById("hours").innerHTML = h;
  document.getElementById("mins").innerHTML  = m;
  document.getElementById("secs").innerHTML  = s;
}
setInterval(currentTime,500);

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

Repeatedly using jQuery to add elements twice

When I run this code, every time I click the '#right' button, the #slide increments by 2 instead of just 1. For example, if there are a total of 6 elements, it displays the 1st, 3rd, and 5th elements. var currentSlide=2; var totalSlides= ...

Searching for a specific key in the Firebase database using AngularFire2 version 5

Currently, I am facing an issue with Firebase as it is providing me keys in a numbered order instead of the specific localStorage IDs that I have stored. These IDs are crucial for accessing nodes in the database. The service I am using has functions desig ...

Encountering a syntax error when attempting to generate a div dynamically with jQuery

I am in the process of creating a view application form using Bootstrap after submitting a form. Initially, I created it utilizing two 'div' elements. Now, I am exploring how to dynamically generate a div upon clicking a button: <i> Sectio ...

Including an anchor element with a specified URL, alongside passing the URL as a property

Having trouble passing a URL to href using a property. I'm attempting to pass the {props.github} value to href, but it's not working as expected. I've set up a property object with a field called github like this: export const projectList ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

Alignment of floating divs along the vertical axis

I am attempting to create a row with three divs positioned side by side: Within the divs, I want the middle one to always be vertically aligned in the middle while the other two are aligned at the top. I initially achieved this using the following settin ...

Challenges encountered with the findOneAndUpdate function

My intention is to send a put request to the /update route. The console.log() messages are being printed in the terminal, confirming that it is working as expected: https://i.sstatic.net/nHyqz.png However, there seems to be an issue with the find one an ...

CSS3's auto property for margin

This is a snippet of my HTML and CSS code that I'm working on: <header id="main"> <a href="#" id="exit"></a> <a href="http://www.reddit.com/" id="reddit"></a> <a href="http://www.stackoverflow.com/" id="st ...

Match the text within a span with the .btn class

I am currently dealing with the .card displayed below and struggling to get the text "You liked this." to align correctly with the Like and Comment .btn-links under the hr element. <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bo ...

I must be patient until the component is visible on the screen, says Protractor

Currently facing an issue where I have to wait for a component to appear on the screen, but sometimes it takes too long to load. Is there a way to wait until a specific field or variable becomes true? element(by.id('nextStage-button')).isPresent ...

Issue arising with Iframe failing to load content on subsequent attempts

I have a situation where I am rendering a partial view through ajax into an iframe within the main view. It works perfectly fine when testing locally, but after publishing it only works the first time and on the second attempt, it clears the body of the if ...

The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute ...

Error: The id provided does not contain information for the 'component' property

Looking to dynamically render different components based on ID in my React app. Currently using a switch case method, but now aiming to customize the header based on the component being rendered. The steps object in App.js is structured like this: ** Here ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...

When increasing the zoom level, the footer becomes oddly centered on the page in Bootstrap 4

I've recently started learning Bootstrap with HTML and CSS. Using the bootstrap grid system, I've created three sections like this. Everything looks good on medium screens or larger. However, a problem arises when viewing on smaller screens (or z ...

What is the best way to ensure that any modifications made to an item in a table are appropriately synced

Utilizing xeditable.js, I am able to dynamically update the content of a cell within a table. My goal is to capture these changes and send them via an HTTP request (PUT) to the backend in order to update the database. Below is the table that can be edited ...

Nested JavaScript function expression

In this JavaScript example, the snippet provided is for educational purposes and does not include validation. After defining the variable 'isBetween' within the buildBoundDetector() function, it raises questions about how passing a number through ...

Achieving a layout with two rows containing two flexboxes on each row using Flexbox

Currently, I'm working on getting two flexboxes on each row. Here is the current layout: https://i.sstatic.net/UsAI6.jpg Here is the desired layout I'm aiming for: https://i.sstatic.net/wRhw4.jpg I want to have 4 flexboxes in total, with 2 on ...

Can the swiping feature be turned off while the image is zoomed in?

For a project, I am utilizing the angular2-useful-swiper wrapper with iDangerous Swiper. I am seeking a way to disable the swiping functionality when an image is zoomed in. After researching the Swiper Api, I have not found any information on how to achie ...

Creating an object with a unique string identifier in JavaScript

In the client, I have declared a namespace and various classes within different namespaces. The challenge arises when I receive a string from the server upon page load containing "dotted" namespace.class names, and I need to obtain an instance of one of th ...