Countdown with precision! This timer will begin at the one-hour mark

Having an issue with my JavaScript stopwatch. When I hit the start button, the stopwatch immediately shows one hour (01:00:00) before counting normally. Any solutions to prevent this instant start at one hour would be highly appreciated. Thank you in advance for a quick response.

<div class="container">
      <h1 class="screen">
        <span id="hours">
          00
        </span>:<span id="minutes">
          00
        </span>:<span id="seconds">
          00
        </span>
      </h1>
      <div class="buttons">
        <button id="start">START CHARGE</button>
        <button id="stop">STOP CHARGE</button>
        <button id="reset">RESET TIMER</button>
      </div>
   </div>
<script>class State {
  constructor(startTimestamp, difference, suspended) {
    this.startTimestamp = startTimestamp;
    this.difference = difference;
    this.suspended = suspended;
  }
  static ready() {
    return new State(0, 0, 0);
  }
}
class Stopwatch {
  constructor(state) {
    this.state = state;
    this.requestAnimationId = null;
    this.handleClickStart = this.handleClickStart.bind(this);
    document
      .getElementById("start")
      .addEventListener("click", this.handleClickStart);
    this.handleClickStop = this.handleClickStop.bind(this);
    document
      .getElementById("stop")
      .addEventListener("click", this.handleClickStop);
    this.handleClickReset = this.handleClickReset.bind(this);
    document
      .getElementById("reset")
      .addEventListener("click", this.handleClickReset);
    this.tick = this.tick.bind(this);
    this.render();
  }

  static ready() {
    return new Stopwatch(State.ready());
  }

  setState(newState) {
    this.state = {...this.state,...newState };
    this.render();
  }

  tick() {
    this.setState({
      difference: new Date(new Date() - this.state.startTimestamp)
    });
    this.requestAnimationId = requestAnimationFrame(this.tick);
  }

  handleClickStart() {
    if (this.state.startTimestamp) {

      return;
    }
    this.setState({
      startTimestamp: new Date() - this.state.suspended,
      suspended: 0
    });
    this.requestAnimationId = requestAnimationFrame(this.tick);
  }

  handleClickStop() {
    cancelAnimationFrame(this.requestAnimationId);
    this.setState({
      startTimestamp: null,
      suspended: this.state.difference
    });
  }

  handleClickReset() {
    cancelAnimationFrame(this.requestAnimationId);
    this.setState(State.ready());
  }

  render() {
    const { difference } = this.state;
    const seconds = (difference ? Math.floor(difference.getSeconds()) : 0)
      .toString()
      .padStart(2, "0");
    const minutes = (difference ? Math.floor(difference.getMinutes()) : 0)
      .toString()
      .padStart(2, "0");
    const hours = (difference ? Math.floor(difference.getHours()) : 0)
      .toString()
      .padStart(2, "0");

    // Render screen
    document.getElementById("hours").textContent = hours;
    document.getElementById("minutes").textContent = minutes;
    document.getElementById("seconds").textContent = seconds;
  }
}

const STOPWATCH = Stopwatch.ready()</script>

Answer №1

Your issue appears to be related to the Date Type. You have set it to a specific time at UTC, but you are retrieving your data with GMT differences.

You might consider using something like this:

var nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

This solution worked for me in the past.

Answer №2

The issue lies in the utilization of the date type due to the attached time zone. Date is not ideal for storing durations, so adjustments were made to make it function properly:

  updateTimer() {
    this.setState({
      elapsedTime: new Date() - this.state.startTime
    });
    this.requestAnimationId = requestAnimationFrame(this.updateTimer);
  }

Additionally,

  render() {
    const { elapsedTime } = this.state;
    const seconds = (elapsedTime ? Math.floor(elapsedTime/(1000) % 60) : 0)
      .toString()
      .padStart(2, "0");
    const minutes = (elapsedTime ? Math.floor(elapsedTime/(60*1000) % 60) : 0)
      .toString()
      .padStart(2, "0");
    const hours = (elapsedTime ? Math.floor(elapsedTime/(3600*1000) % 60) : 0)
      .toString()
      .padStart(2, "0");

    // Update display
    document.getElementById("hours").textContent = hours;
    document.getElementById("minutes").textContent = minutes;
    document.getElementById("seconds").textContent = seconds;
  }

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

acquiring data via fetch (transferring information from javascript to php file)

I'm completely new to using fetch and not familiar with Ajax. Currently, I am attempting to transfer data from a JavaScript file (node.js server) to a PHP file (Apache server). The data being sent consists of 2 JSON values labeled as "a" and "b". T ...

Automatically update the table in Python Flask every minute

I need help with my Flask code below. I want to automatically refresh the table data every 60 seconds. I have included the Setinterval function in HTML, but for some reason, it's not refreshing as expected. I'm struggling to pinpoint the exact is ...

Issue with Material-UI DataGrid Component: Unable to access property 'length' as it is undefined

I need to display my JavaScript Object Data in a table format with pagination and sorting capabilities. I have chosen the DataGrid component from Material UI, but I am encountering some errors. Below is the code snippet: import React from 'react&apos ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

How can I determine the size of the custom options dropdown in Magento?

I'm facing a challenging issue that I can't seem to crack. It might be because I'm still learning the ropes and struggling with technical jargon. Please bear with me as I try to explain my problem. Here is a summary of what I'm trying ...

Error: The function jQuery(...).hexColorPicker does not exist

I am attempting to utilize a color-picker jQuery plugin. Below is a screenshot of the JavaScript file: https://i.stack.imgur.com/ovRjx.png Here is the code I am using to initialize it: <script type="text/javascript> jQuery(function(){ ...

What is the best way to display an object in Vue.js once it has been retrieved through an AJAX request?

Imagine having the following HTML code: <div id="app"> <h2>List of Items</h2> <table border="1"> <thead> <tr> <th>Name</th> ...

Retrieving an Angular Application directly from the Server

In order to ensure user authentication from the backend before any other code loads in my Angular app, I need the initial request sent to the backend to check if the user is authenticated. Only once the user has been verified as authenticated can the app b ...

Vue.js - when it comes to rounding off digits, I keep getting unexpected results

Currently, I am in the process of calculating my totals and I need to ensure that they are fixed to 2 decimal places. Here is a snippet of my code: this.selectedCompaniesDetails.forEach((company) => { if(company.id == p.compa ...

Switch up the key while iterating through a JSON object

Can you modify the key while iterating through objects using an external variable? Picture it like this: var data = [{ "id": 1, "name": "Simon", "age": 13 }, { "id": 2, "name": "Helga", "age": 18 }, { "id": 3, "name": "Tom ...

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...

Choosing the state object name dynamically within a React JS component

I have a quick question about updating state in React. How can I change a specific object in a copy of the state that is selected using e.target.name and then set to e.target.value? For example, if I want to change newState.age when e.target.name = age i ...

angular: handling duplicates in ng-repeat

Here is the JSON data: streams = [{ id: 0, codec_type: 'video', content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' }, { id: 1, codec_type: 'audio', content: '5.1(side) - cze - undefined' }, ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

Position the label and the select dropdown side by side within the sweetalert 2 component

Can anyone provide an example of aligning a label and dropdown in the same row using sweetalert2? I attempted to customize the label placement, but it appears on a separate line. I would like to log the selected dropdown item upon clicking the OK button. ...

React: Updating useState array by removing the first element triggered by an event or timer

I am currently working on a function that populates a useState array containing objects representing cars. These cars appear on the left side of the screen and move across until they are off-screen. My goal is to remove these cars from the state array once ...

I'm having trouble customizing the appearance of a Tab Panel using the TabsAPI. The panel keeps expanding in strange ways. How can I

Trying to customize the Tabs component from MUI is proving to be a challenge. The main issue I am facing currently is: Whenever I switch between tabs, they appear to expand in size mysteriously. This behavior seems to occur only on tabs with more content ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...