Utilizing Javascript for a Stopwatch/Countdown in the Format: 00:00:00

I am currently working with this block of code:

    function startStopwatch() {
        vm.lastTickTime = new Date();

        $interval.cancel(vm.timerPromise);
        vm.timerPromise = $interval(function() {
            var tickTime = new Date();
            var dateDiff = vm.lastTickTime.getTime() - tickTime.getTime();
            var secondsDiff = Math.abs(dateDiff / 1000);
            vm.secondsElapsed += Math.round(secondsDiff);
            vm.formattedSecondsElapsed = moment.duration(secondsElapsed, "seconds").format("HH:mm:ss");
            vm.lastTickTime = tickTime;
        }, 1000);
    }

This code tracks the number of seconds since hitting the 'play' button on a stopwatch.

The current format increments as 01, 02.... up to 60 and then switches to 01:01, 01:02, etc.

My goal is to have it formatted as 00:00:00, incrementing the integer. I have searched for solutions in different programming languages but haven't found one specifically for JavaScript. Any suggestions or assistance would be greatly appreciated!

Answer №1

Adapting the solution shared by RJB, simplify the algorithm into a filter:

Custom Filter

app.filter('time', function() { 
    function isInteger(number){
        return Number(number) === number && number % 1 === 0;
    }
    return function(value) {
        if (isInteger(value))
            return new Date(null, null, null, null, null, value).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

        return value;
    }
});

Implementation

app.controller('ctrl', function($scope) {
    $scope.seconds = 25251;
});

HTML Markup

<div ng-controller="ctrl">
      {{ seconds | time }}
</div>

View Demo Plunker

Answer №2

After careful consideration, I have decided to restore this response as it is deemed the most suitable and holds educational significance.

vm.timeElapsed = new Date(0, 0, 0, 0, 0, secondsPassed).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

Origin of answer:

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

The form is unable to detect invalid fields because of a nested view and inherited model structure

Currently in my project, I am utilizing Angular UI's ui-router for handling nested views. Specifically, within my layout on a distinct record page, the structure is as follows: Upon initial loading, everything functions smoothly - validation works, c ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

AngularJS Filter from "start to finish" in values

I have been searching everywhere for a solution to this problem, but haven't found one yet. Any help would be greatly appreciated. Angular: var app = angular.module('app', []); app.controller('theController', ['$scope', ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

How can I integrate Apple remote support into a website with the use of Javascript?

One thing that I find interesting is the ability to use the Apple remote with Front Row, as well as other apps on Mac that support it. I'm curious about whether Web Apps could also be made compatible through Javascript. I have a concept for a TV-like ...

What is the best approach to modifying array elements using onChange and hooks in React?

I'm struggling to implement something simple, and the solutions I've found so far don't quite address my specific issue. Here's the state in question: const [formFields, setFormFields ] = useState({ formTitle: '', fiel ...

Reading and decoding JSON data using AJAX

Upon viewing the console, I receive the JSON data in the following format: [Object] 0: Object address: "soham" region: "soham" relevanceScore: "4" startDate: "2015-05-10" subscriptionType: "1" verificationStatus: "1" __pro ...

Is the input in the array? How to find out?

I am currently facing an issue with a script that I have created to count array elements matching a user input. Strangely, all if statements in the script seem to be returning false. I have verified that both the array element and the input value are stri ...

:onchange event triggering iteration through a function

My Vue.js application is experiencing issues with infinite post requests when a selectbox value changes. I have a table component that needs to display students from different 'tutorgroups'. Each tutorgroup, like '4M07a', has its own se ...

Unable to perform surveillance on the htpp.get method

Example snippet: if (!this.scope.popupHtmlTemplate) { this.$http.get("widgets/pinpointcomponent/browseLibraries/resources/browseLibrariesDialogModal.html") .success((data: any) => { console.log("Processing success"+data) if (dat ...

Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests. I am in the process of implementing a route guard to ...

Error message: Unable to locate the 'npm' task in Visual Studio Code

When attempting to execute a JavaScript or Python file in VS Code, an error message consistently pops up: Even after reinstalling node, the issue persists. Clicking on configure reveals various options, each leading me to a json file. New to coding, I ma ...

Enabling deep linking with $locationProvider.html5Mode in AngularJS

After activating html5Mode in AngularJS with $locationProvider.html5Mode(true), the navigation appears to be off when arriving on a deeper page within the site. For instance: http://www.site.com When navigating to the root, all links on the site are ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...

Is an empty string equivalent to false in a boolean context?

I would appreciate further clarification on this subject. I have read several articles, but none have fully answered my questions. ...

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

Error in content policy for CSS in Stripe Checkout

I am currently attempting to integrate Stripe Checkout into my Ionic App. I have created a Directive that injects the form into my content view, however, upon execution, the CSS fails due to a content policy violation: checkout.js:2Refused to load the s ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

How can markers be filtered on a Google Map API without the need to refresh the map?

I have created an Angular JS module that utilizes the Google Map API. The map is defined as a global variable, along with a global array for markers, and functions for managing these markers such as removing them, resetting the map, and adding new markers. ...