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

JavaScript recording speed

I am currently working on a project that involves video recording on my website. After creating a canvas and pushing the recorded frames to it, I have encountered an issue. The playback of the video is too fast - a 10-second video plays in around 2 second ...

Exploring the power of JQuery's $.post() function and the magic

In order to utilize the GroupMe API (), the following command is required: $ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN I ...

The jQuery date picker is showing an error with the function daySettings[2].replace, indicating that

Encountering a problem with the jQuery version I am using: <script src="js/Common/jquery-2.1.1.min.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> The code I have writte ...

Using JQuery, identify cells located in the first column of a table excluding those in the header section

In the past, I had code that looked like this: $(elem).parents('li').find(...) I used this code when elem was an item in a list, making it easy to reference all items in the list. But now, I've made some changes and decided to use a table ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

JavaScript: Identify the variable that has been updated

When checking for changes in the values of a couple of variables, I use the following condition: <% if (ctx.recipient.@firstName != ctx.recipient.@firstName_init || ctx.recipient.@lastName != ctx.recipient.@lastName_init || ctx.recipient.@emailPreferred ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

Adjusting package.json settings for an npm module

An npm package that I am using has an incorrect file path specified in its package.json. The current configuration is: "main": "./htmldiff.js", However, for it to function correctly, it should be: "main": "./src/html ...

Scraping with Node.js and PhantomJS for dynamic content

After successfully installing both PhantomJs and its npm interface phantom, I have set the code to load my desired page with the updated syntax. However, for some reason, the dynamically generated elements in the right sidebar are not being picked up by ph ...

I am looking to update the background color of the material UI helper text

In the image below, you can see that my background color is gray and my text field color is white. When an error is shown, the text field's white color extends and the password error message doesn't look good. I want the text field to remain whit ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

How to Add Motion to Several Markers

Exploring the concept of moving markers on a map with drawn polylines to simulate simultaneous movement is a fascinating challenge. However, encountering some difficulties, such as only the last marker moving while the others remain stationary, can be frus ...

Exploring the contents of this JSON array

I'm trying to fetch data from this link: <script type="text/javascript"> $.getJSON('http://api01.notaion.com/?item&id=120001462', function(data) { }); </script> I am uncertain whether I need to use a callback=?, a ...

javascript dynamic content remains unaffected by ajax call

I'm a beginner with javascript and I am using a PHP variable to create links dynamically. Here is an example of how the variable is set: $addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart(' ...

Vue alert - Cannot access indexOf property of a value that is undefined

After browsing through numerous similar issues on StackOverflow, none seem to address the specific problem I encountered... I have been smoothly working on a Vue JS project + Laravel until I suddenly encountered an error that seems unsolvable (even though ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

Vue.js - experiencing issues with conditional styling not functioning as expected

Can someone help me with an issue I'm having? I've created a button with a heart symbol that is supposed to change color when clicked, but it's not working as expected. This is my current code: <template> <button v-bind: ...

Displaying checkbox values with JavaScript

How can I display multiple checkbox values when checked in HTML code? Whenever I check a checkbox, I want its value to be shown alongside the previously checked values. Right now, my code only displays one value at a time. Any suggestions on how to achie ...

jQuery fade in problem or alternate solutions

When I send a post request to a file and input the response into id='balance', I would like it to have a flickering effect or fadeIn animation to alert the user that it is being updated in real time. I attempted to use the fadeIn() method but it ...

how to choose the :after pseudo-element with jQuery

Below are the codes I have tried. When this popup appears, I want to be able to close the entire popbox using the close button. CSS code .bigdiv{ display:none; background-color:#efefef; box-shadow: 10px 10px 10px 100000px rgba(0, 0, 0, 0.4); ...