Trouble with setInterval not refreshing the HTML element

I'm currently working on a script that should update the value of an element every second. However, I've encountered an issue where the element only updates the first time and then stops. Strangely, there are no errors appearing in the console either.

What's even more puzzling is that the console.log() function continues to run, but the element and the time variable don't seem to update.

var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');

setInterval(function() {
  time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  var elTime = document.getElementById("time");
  elTime.textContent = time;
  console.log(time);
}, 1000);

Answer №1

One way to tackle this is by ensuring that the variables are updated each time the setInterval function runs.

(function() {
  setInterval(function() {
    var today = new Date();
    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
    time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var elTime = document.getElementById("time");
    elTime.textContent = time;
    console.log(time);
  }, 1000);
})()
<div id="time"></div>

Answer №2

Make sure to update the time display constantly within the interval. Modify your code like this:

setInterval(function(){
   var now = new Date();
  currentTime = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
  var elementTime = document.getElementById("time");
  elementTime.textContent = currentTime;
  console.log(currentTime);
}, 1000);

Answer №3

A basic setInterval program in action can be seen below.

setInterval(() => {
  var updateTime = document.getElementById("time");
  updateTime.textContent = parseInt(updateTime.textContent) + 1;
}, 1000);
<div id="time">0</div>

All code to be executed should be contained within the setInterval function's scope. Make sure to include your entire script inside the function's scope for it to run regularly, like so:

setInterval(function() {
  //Variables
  var currentDateTime = new Date();
  var timeNow = currentDateTime.getHours() + ":" + currentDateTime.getMinutes() + ":" + currentDateTime.getSeconds();
  var dateToday = currentDateTime.getFullYear() + '/' + String(currentDateTime.getMonth() + 1).padStart(2, '0') + '/' + String(currentDateTime.getDate()).padStart(2, '0');
  timeNow = currentDateTime.getHours() + ":" + currentDateTime.getMinutes() + ":" + currentDateTime.getSeconds();
  var elTimeUpdate = document.getElementById("time");
  elTimeUpdate.textContent = timeNow;
  console.log(timeNow);
}, 1000);
<div id="time"></div>

Answer №4

SetInterval is a mechanism for calling functions at specified intervals.

It's important to note that SetInterval cannot guarantee precise timing, as the time between each invocation is more of an approximation for the browser to use. Depending on other tasks that need to be executed, the actual interval may be longer than what was initially requested. This variance can result in delays of a few milliseconds or even more.

If you are looking for easy-to-use native JavaScript time formatting, check out this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

const elTime = document.getElementById("time")

ShowTime()                    // initial display
setInterval(ShowTime, 1000)  // subsequent updates

function ShowTime()
{
  let currentTime = new Date()
  elTime.textContent = currentTime.toLocaleTimeString('default', { hour12:false } ) 
}
<p id="time"></p>

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

Challenges encountered with Material-UI elements

Attempting to implement the http://www.material-ui.com/#/components/drawer (Docked Example) component from Material-UI in conjunction with ReactJS. An error is encountered with the "=" sign in this line: handleToggle = () => this.setState({open: !this ...

How can you ensure that the Data Point Values are always displayed when using arrayToDataTable in the Google Charts API?

Just wanted to clarify that even though there is a similar question titled: Google Charts API: Always show the Data Point Values in Graph ...on this website, I am facing difficulties implementing its solution because my chart is using arrayToDataTable. ...

JavaScript Promise Synchronization

I have a JavaScript function that returns an object using promises. The first time the function is called, it fetches the object, but for subsequent calls, it returns a cached instance. To simulate the fetching process, I've added a delay. var Promis ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

Scrolling with animation

While exploring the Snapwiz website, I came across a captivating scroll effect that I would love to implement on my own site. The background picture changes seamlessly as you scroll, with the front image sliding elegantly into view. A similar type of scro ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Customize the theme of Ant Design for VueJS

I have successfully set up my Vue3 application with Tailwind and Ant Design. However, I am facing issues with customizing the Ant Design theme. I have been referring to this guide. When trying to customize the theme, I encountered the following error: Err ...

What is the best way to prevent labels from floating to the top when in focus?

How can I prevent the label from floating on top when focusing on a date picker using Material UI? I have tried several methods but nothing seems to work. I attempted using InputLabelProps={{ shrink: false }} but it did not resolve the issue. Here is a li ...

Using Formik with Material UI's TextField component and passing a 'label' prop to the Field component

Currently, I am in the process of creating a form with Formik and Material UI. I have implemented the Formik component as follows: Within my Input component, the following code is used: const Input = ({ field, form: { errors } }) => { const errorMes ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

Run JavaScript code before finalizing the "submit" action within a Ruby on Rails application

Having trouble with utilizing old JS scripts found on Stack Overflow. <div class="form-actions"> <%= f.button :submit, class:"btn btn-success create-campaign" %> </div> The submit button is causing an issue for me. <div clas ...

I am having issues with Hot Reload in my React application

My app was initially created using npx create-react-app. I then decided to clean up the project by deleting all files except for index.js in the src folder. However, after doing this, the hot reload feature stopped working and I had to manually refresh the ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Check if the element is located on the active tab using jQuery

I have implemented a tab system to organize a lengthy form with multiple input fields. The form consists of 4 tabs, and beneath them, there is a preview section displaying the user's selections. In this preview area, I added icons that enable users ...

Showing or hiding child content based on the selected state of a radio button

This is a follow-up question from a previous one on changing check boxes to radio buttons. Now, I need to display child radio buttons and change the background color when the parent radio button is active. The child radio buttons should be hidden and the b ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...

The Vuejs single-file component fails to display on the page

Even though there are no errors in the browser and Webpack compiles successfully, the message "hello from dashboard" is not displaying on the page. I am currently using Vue version 2.6 In my main.js file: import Vue from 'vue' Vue.component(&a ...

To prevent the background window from being active while the pop-up is open

I have a link on my webpage that triggers a pop-up window, causing the background to turn grey. However, I am still able to click on other links in the background while the pop-up is open. I tried using the code document.getElementById('pagewrapper&ap ...

Select from a list to save

My goal is to create a feature where users can select a hotel name, number of days, guests, and peak time, the system will calculate them together and give a sum. Furthermore, I wish to store all user selections in the database, including the calculated to ...