The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more).

Below is the code snippet I used:

  getTime() {

    const time = new Date();

    const formatter = Intl.DateTimeFormat('de-AT', {
        hour: "2-digit",
        minute: "2-digit"
    });

    return formatter.format(time);
  }

  updateClock() {
    this.clock = this.getTime();
  }

This function is called within a setInterval method:


 setInterval(() => {
      this.updateClock();
    }, 1000);

I'm puzzled as to why the time discrepancy occurs after some time has passed. Given that I create a new Date object each time, it should theoretically maintain accurate timekeeping.

EDIT: Upon further investigation, it appears that the inaccuracy stems from the internal clock of the TV itself, which drifts out of synchronization over extended periods (for unknown reasons). As the JavaScript DateTime relies on the TV's system time, which is incorrect, the displayed clock also becomes inaccurate.

Answer №1

Timers don't always run exactly when you expect them to. Sometimes there can be delays, especially with setInterval set to one second intervals.

If your timer is off by more than seconds, you may have too many intervals running at once and not storing the value for clearInterval. To fix this, try reducing the interval or using a delay of 1000 / 60 (60 FPS) instead. If it still doesn't work properly, it may be due to the browser or device saving power by pausing intervals until you interact with the main window again.

Try adjusting the interval timing to see if that helps improve performance based on the specific needs of your code and environment.

Answer №2

In order to efficiently manage the interval, I suggest storing the identifier returned by setInterval. This way, you can easily start and stop the interval when needed.

By updating the current time every second, you can ensure that the formatted time is accurate at all times.

Here's an improved example showcasing the use of a class:

class ClockManager {
  constructor({ formatter, renderer }) {
    this.formatter = formatter;
    this.renderer = renderer;
    this.time = '';
  }
  update() {
    this.time = this.formatter.format(new Date());
    if (this.renderer instanceof Function) {
      this.renderer(this);
    }
  }
  start() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    this.update(); // Initial call
    this.intervalId = setInterval(() => {
      this.update(); // Call every second
    }, 1000);
  }
  stop() {
    clearInterval(this.intervalId);
    this.intervalId = undefined;
  }
}

const clockElement = document.querySelector('#clock');

const clockInstance = new ClockManager({
  formatter: Intl.DateTimeFormat('de-AT', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }),
  renderer: (clockRef) => {
    clockElement.innerText = clockRef.time;
  }
});
clockInstance.start();
<div id="clock"></div>

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

Encountering an "AJAX not a function" error while using the d3/flask interface

Hey there! I'm new to the world of JavaScript and AJAX. Take a look at this d3 function I've been working on: var node = g.selectAll(".node") .data(root.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Troubleshooting Guide: Issues with Bootstrap 3 Modal Window Implementation

This question is so simple that it's embarrassing. I attempted to copy the code from http://getbootstrap.com/javascript/#modals directly into a basic page setup, but it's not functioning. It seems like I'm making a very silly mistake. Here i ...

Is React the ideal choice for implementing a shared state subscription mechanism in your project?

Trying to determine if this falls under the "pub/sub" pattern or a variation of it. The goal is to establish a shared state where different components can subscribe to it and only receive updates when the state changes. const useForceUpdate = () => useR ...

The input field does not accept any values even after setting it to be editable

Hey there! I have a specific requirement where I need to edit certain fields by clicking on an edit link. Initially, these fields will be disabled and in a readonly state. Once I click on the edit link, the field should become blank and editable. The issu ...

JavaScript class name modifications are not functioning as expected

Testing a sprite sheet on a small web page I created. The code for each sprite in sprites.css is structured like this... .a320_0 { top: 0px; left: 0px; width: 60px; height: 64px; background: url("images/sprites.png") no-repeat -787 ...

`A brief disruption in loading the visual style of Google Maps`

Using the Ionic Framework, AngularJS, and Google Maps API, I encountered an irritating issue with my mobile app. Every time the map loads, there is a noticeable delay in loading the map style. This delay is particularly problematic as my map style converts ...

Exploring Nested Objects within a v-for Loop

My API is returning an array of objects, where each object has the following structure: { id: 6, typeTitle: 'Type Title goes here', typeImg: 'Some image', typeLink: 'https://www.somewebsite.com', publishDa ...

Issue with format: The time data '22.12.2012 17:00' does not align with the specified format '%d.%m.%Y %I:%M', am/pm

I'm facing a challenge in parsing a string into a datetime object in Python. The code snippet below works for some values, but not always, and I can't figure out what's wrong with it. datetime.datetime.strptime("22.12.2012 17:00", '%d. ...

Please ensure you have selected at least one item before submitting the form

I have been working on validating a form using a combination of bootstrap and angularjs. The form includes two groups of checkboxes that need to be validated. It is required for the user to select at least one checkbox from each group in order for the Subm ...

Experienced an unexpected setback with the absence of the right-click capability on a Javascript-powered hyperlink, specialized for

I am facing an issue with a hyperlink on my website. This particular hyperlink submits a hidden form using the POST method to redirect users to another site. However, when someone right-clicks on this hyperlink and tries to open it in a new tab, they are o ...

Seamless scrolling experience achieved after implementing a header that appears when scrolling up

My goal is to create a header with the following functionalities: Initially displays with a transparent background Upon scrolling down the page by 25px, it will dynamically add the header--maroon class to the header, which alters the background color and ...

Stop the interval when hovering and start the interval when moving the mouse away

I've managed to create a carousel that automatically slides every 5 seconds, with manual buttons to navigate the slides. My goal is to pause the scrolling when the mouse hovers over a slide and resume once it's no longer hovered. Currently, my s ...

Using knockout to retrieve the attribute value with an onClick event

Snippet of HTML View with attribute value 'Qref'. This is the sample HTML Code for binding Currently, I have manually inputted the Qref Attribute value <!--ko if:$parent.Type == 2 --> <input type="checkbox" data-bind="attr:{id: $data ...

Is there a way to pass the ng-repeat value or ID to my dynamically appended element? If so, how can I achieve

I am working on a project where I have a table with 5 data entries retrieved from a select query. My goal is to extract the ng-repeat value and ID, then transfer it to another element. As a beginner in Angularjs and HTML, I would greatly appreciate any ass ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

Dynamically showing a div using JavaScript and AJAX after changing the window location

After successfully fetching data from the server through AJAX, I am redirecting to the same screen/URL. Is it possible to show/display a div after redirecting using jQuery? $.ajax({ type: "POST", url: action, data: form_data, success: func ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

React - the use of nested objects in combination with useState is causing alterations to the initial

After implementing radio buttons to filter data, I noticed that when filtering nested objects, the originalData is being mutated. Consequently, selecting All again does not revert back to the original data. Can anyone explain why both filteredData and orig ...