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

I have a parent DIV with a child DIV, and I am looking to use jQuery to select the last child DIV. The parent DIV has an

In my HTML code, I have a parent div called "allcomments_4" which contains several child divs with unique IDs (oneEntry), each with their own children. My goal is to locate and retrieve the content inside the last child of the parent node (lastComment) and ...

When using NodeJS with expressJS, remember that req.body can only retrieve one variable at a

I'm having trouble with my login and signup pages. The login page is working correctly, but the signup page is only transferring the password for some reason. App.JS: var express = require("express"); var app = express(); var bodyParser = require("bo ...

Iterate through and conduct conditional verification

In my project using AngularJS and HTML, I have created a table to display records. I am looking for a way to iterate through the column values and strike through any value in the column that meets a certain condition. For example, in the demo provided her ...

Retrieving data in Next.js

Exploring various techniques to retrieve information from APIs in next.js. Options include getServerSideProps, getStaticPaths, getStaticProps, Incremental Static Regeneration, and client-side rendering. If I need to send requests to the backend when a s ...

Display an empty string when a value is NULL using jQuery's .append() function

To set an HTML value using the .append() function, I need to include AJAX data values. If the data set contains a null value, it will show as 'null' in the UI. I want to remove that 'null' and display it as blank. However, I can't ...

Mastering the art of bi-directional data binding with nested arrays in Angular

Imagine you have a to-do list with various tasks, each containing multiple subtasks. You want the ability to change the subtask data, but why is Angular not properly two-way binding the data for the subtasks? HTML <div *ngFor="let task of tasks"> ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

Whenever a new entry is made into the textfield, the onChange feature triggers a reset on the content within the textfield

I'm experiencing an issue while creating a SignUp authentication page with Firebase. Every time I try to input text in the text field, it gets reset automatically. I have been unable to identify the root cause of this problem. It seems to be related t ...

Combining react-draggable and material-ui animations through react-transition group: a comprehensive guide

Trying to incorporate react-draggable with material-UI animations. One approach is as follows: <Draggable> <Grow in={checked}> <Card className={clsx(classes.abs, classes.paper)}> <svg classN ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

Looking for assistance in resolving performance problems with numerous elements in AngularJS

I am currently experiencing performance issues with AngularJS, particularly when a large number of "elements" are added to the page. It is taking around 20 seconds for my computer to render the elements in this folder structure. Each folder contains 10 sub ...

Having trouble with updating links in HTML pages?

I'm having trouble updating all the links in my HTML file. The code I have isn't working as expected. var fs = require('fs'); fs.readFile(__dirname + '/index.html', 'utf8', function(err, html){ if(!err){ html = ...

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

The componentDidUpdate method is functioning by comparing the previous state with the current state on different triggers

I have a primary element that is invoking another element with specific attributes. // Primary Element <SecondaryElement className="EnterNumber-input" submitClicked={this.state.submitClicked} /> Upon clicking a button, I am modify ...

Invoke a component and initiate a click event from within the App.vue component

Within my template, there is a click event: <span v-on:click="showGalery()"> This event is linked to the following method: export default { name: 'osaka', data: function () { return { galery: false, } }, methods: { ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

AngularJS retrieves entire video file for HTML5 video tag

I am currently developing a web application with AngularJS where the main page showcases five videos for the user to choose from and play. However, I have encountered an issue where all source video files are being downloaded for each HTML5 video element d ...

Seeking help with executing JQuery Ajax functions within a foreach loop

Currently, I am engrossed in the study of programming and endeavoring to construct a website utilizing .Net Core. The predicament at hand pertains to my limited acquaintance with JavaScript while incorporating two JQuery/AJAX functions on my Index page - o ...

Tips for parsing form values using jQuery AJAX:

Is there a way to extract form values and check if 15 objects have values or not? I attempted to do this using jQuery.parseJSON() but it didn't work as expected. [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Obj ...