Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult.

This is what I have so far, but I suspect the issue lies within the h variable.

function formatTime(time) {
      var h = m = s = ms = 0;
      var newTime = '';

      h = Math.floor(time / (60 * 1000))
      m = Math.floor(time / (60 * 1000));
      time = time % (60 * 1000);
      s = Math.floor(time / 1000);
      ms = time % 1000;

      newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
      return newTime;
      }

Providing the complete JS code below:

<script type="text/javascript">
      var clsStopwatch = function () {

      var startAt = 0;
      var lapTime = 0;

      var now = function () {
          return (new Date()).getTime();
      };

      this.start = function () {
          startAt = startAt ? startAt : now();
      };

      this.stop = function () {
          lapTime = startAt ? lapTime + now() - startAt : lapTime;
          startAt = 0;
      };

      this.time = function () {
          return lapTime + (startAt ? now() - startAt : 0);
      };
      };

      var x = new clsStopwatch();
      var $time;
      var clocktimer;

      function pad(num, size) {
      var s = "0000" + num;
      return s.substr(s.length - size);
      }

      function formatTime(time) {
      var h = m = s = ms = 0;
      var newTime = '';

      h = Math.floor(time / (60 * 1000))
      m = Math.floor(time / (60 * 1000));
      time = time % (60 * 1000);
      s = Math.floor(time / 1000);
      ms = time % 1000;

      newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
      return newTime;
      }

      function show() {
      $time = document.getElementById('time');
      update();
      }

      function update() {
      $time.innerHTML = formatTime(x.time());
      }

      function start() {
      clocktimer = setInterval("update()", 1);
      x.start();
      }

      function stop() {
      x.stop();
      document.getElementById('counter').value = formatTime(x.time());
      clearInterval(clocktimer);
      }
      </script>

Answer №1

To properly assign the value of h, use the following formula:

h = Math.floor(time / (3600 * 1000));

Don't forget to include this line as well:

time = time % (3600 * 1000);

This should be done before calculating the minutes to ensure you obtain the accurate total number of minutes.

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

Issue with displaying custom in-line buttons in JQGrid

Currently, I am utilizing jqgrid 3.8.2 (I am aware it's not the latest version, but I plan on updating it soon after seeking some advice :-)) I have successfully incorporated a couple of in-line buttons into my jqgrid using the default formatter &apo ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

What is the best way to update information in a mongoose document using the _id field?

Although it may sound like a typical question, I've already conducted research and couldn't find a solution. I'm currently working on developing a discord bot and I don't have much experience in this area. The issue I keep encountering ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

Activate SVG graphics upon entering the window (scroll)

Can anyone assist me with a challenging issue? I have numerous SVG graphics on certain pages of my website that start playing when the page loads. However, since many of them are located below the fold, I would like them to only begin playing (and play onc ...

The issue with fetching user profile data on the client-side in Next.js 14

I've run into a problem with client-side data fetching on my Next.js 14 project. More specifically, I'm trying to retrieve user profile information from a backend API using Axios within a component, but for some reason, the data isn't coming ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Comparable user interface on par with what we find on Windows Phone 7

I'm quite impressed with the innovative interface experience of Windows Phone 7. It stands out compared to other interfaces, whether on mobile devices, desktops, or the web. Despite its uniqueness, it remains highly usable. Overall, a great step in th ...

What is the reason for the error that Express-handlebars is showing, stating that the engine

I recently added express-handlebars to my project and attempted the following setup: const express = require("express"); const exphbs = require('express-handlebars'); const app = express(); app.engine('.hbs', engine({defaultL ...

I must design a unique layout for my website

I am creating a webpage with various shapes and elements. However, I am facing a challenge with creating a shape that is commonly used. In platforms like Khan Academy, there is simulated programming where shapes can be easily created with a simple command ...

Can someone break down the meaning of "returning $http.post" in Angular while developing a factory service?

I've been grappling with the concept of return $http.post('/some link') and can't seem to fully grasp it. Imagine I have a node/express backend and am utilizing Angular for my frontend. Within my api, there is a function like this: v ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

What advantages does declaring a backing model "class" that closely resembles the GraphQL "Type" bring when using GraphQL?

I appreciate the Universal Relay Boilerplate for its meticulous organization and thoughtful structure compared to other boilerplates. It seems like they really put a lot of effort into ensuring everything is well-planned from the start, which is not always ...

Issue with MomentJS inBetween function consistently displaying incorrect results

I'm currently working on Vue Datatable and I have a specific requirement to search for records between two dates. I am using the moment.js library and the inBetween function to achieve this. Strangely, when I hardcode the dates, the function returns t ...

Tips for including HTML in a JSON request in ReactJS

Upon sending the request as shown below, the response was successfully received. { "contractId": "siva8978", "html": "<p>PREFERENCE SHAREHOLDER AGREEMENTTHIS AGREEMENT is made on the&nbsp;$$Contract Start Date$$ BETWEEN&nbsp;CRADLE WEALTH ...

jQuery can't capture form submission

I've been trying to implement this seemingly simple piece of code, but no matter what I do, it just won't work. I've followed several examples online and even tested it on both IE and Chrome without success. One thing that did work was testi ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. T ...

Having trouble loading images in JavaScript due to an issue with JSON: undefined.jpg not found

I'm struggling to concatenate my image names in this JavaScript code as a newbie, especially since it's pulling from JSON. Any assistance would be greatly appreciated! Below is the JS code snippet I'm working with: function log(msg){ ...