Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should change accordingly.

    /* Stopwatch */
    starttime(){
        console.log("timer started");
        if( this.running == 0){
            this.running = 1;
            this.adder()
        }else{
            this.running = 0;
        }
   }

    reset(){
        console.log("timer reset");
        this.running = 0;
        this.time = 0;
        this.total = 0;
        this.Sec = 0;

    }

    adder(){

        console.log("timer incrementor");
        if(this.running == 1){
            setTimeout(()=>{ 
                this.time++;
                var mins = Math.floor(this.time/10/60);
                var sec = Math.floor(this.time / 10 ) % 60;
                var tens = this.time/10;

                this.total =  mins + ':' +  sec;
                console.log(this.total) ;
                this.Sec = sec;               
                this.adder()  

            },100)
        }

    }   

Initially, the time would continue to increase without resetting at 60 seconds, leading to incorrect timestamps like 0:2:120 after 120 seconds. To address this issue, I modified 'var sec = Math.floor(this.time / 10)%60;' and adjusted the timeout value to 100ms.

Answer №1

If you have the chance, consider utilizing moment.js for formatting the time that has passed.

this.total = moment.utc(this.time).format("mm:ss.SSS"))

If not, feel free to disregard this response ;)

Answer №2

It appears that there may be an error in your calculation for the second variable. Consider using the following code snippet instead of your current one:

let sec = Math.floor(this.time / 10) % 60;

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

What is the process for assigning variables to modules using RequireJS?

Is there a way to define variables for modules in RequireJS? In simpler terms, how can I achieve the equivalent of the following using RequireJS: var fs = require('fs'); var child_process = require('child_process'); I am looking to s ...

Fetching data from a ColdFusion component using AJAX

Having trouble performing an SQL COUNT on my database using AJAX through a cfc file, and I can't figure out how to retrieve the return variable. Here's the relevant section of the cfc file: <cffunction name="getSpeakerCount" access="remote" r ...

Challenges encountered when using setState to assign values

Just started using React and running into an issue with updating state when changes are made to a Textfield. I'm working with a functional component where the initial state is set using useState. I feel like I might be overlooking something simple... ...

My attempt at utilizing the regex function was unsuccessful

When attempting to use a regex function for matching tags in the title and caption, it appears to work fine. However, adding more matching tags causes the function to fail. Below is the code snippet that functions correctly without any issues: $(".si ...

jQuery is unable to manipulate newly added DOM elements that have been loaded via AJAX

Having trouble with jquery ajax. Unable to interact with newly added element through ajax. Code snippet: $(".yorum_input").keypress(function(e) { if (e.keyCode == 13) { e.preventDefault(); var alt_id = $(this).attr('yorum_id'); va ...

System for Node.js execution replay logging

Running a straightforward script that performs various tasks can be tedious when trying to debug errors. The log messages scattered throughout the code clutter the file, requiring more and more console.log entries for detailed information. Instead of fill ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...

The revalidateTag and revalidatePath features in Next.js are currently not functioning as expected

I attempted to utilize the revalidateTag and revalidatePath functions with Next.js version 14.2.3. The objective was: there is a server action to fetch a list of items. also, there is a server action to add an item. upon successful addition of an item, I ...

A stylish flyout menu with a sleek li background in jquery

Experimenting with http://tympanus.net/Tutorials/CufonizedFlyOutMenu/, I decided to remove the fly-in descriptions and am now attempting to load the extra li with a style that will "highlight" the li.current-menu-item element. An object is set up as follo ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

Encountered an import error when using "npm run build", but it runs successfully with "npm start"

My React app is running smoothly with npm start, but I encounter an error when trying to build it using npm run build. The error message I receive is: `Creating an optimized production build... Failed to compile. Attempted import error: './parseq-lan ...

The image is experiencing difficulty loading from the Express static directory

Having some trouble with image loading... I've noticed that images are loading fine from the local folder, but not from the uploads folder which is set to be static. I've been attempting to upload a file from the browser. The upload and save pr ...

What are the reasons for the various methods available for importing my JS code?

Here is the structure of my folders: --public ----frontend.js --views ----fontend.ejs The frontend.js file is located inside the public folder, while the frontend.ejs file is in the views folder. In my HTML / EJS file, I included the JavaScript (fronten ...

What is the best way to update just the image path in the source using jQuery?

I am currently working on implementing a dark mode function for my website, and I have successfully adjusted the divs and other elements. However, I am facing an issue with changing the paths of images. In order to enable dark mode, I have created two sep ...

Perform an addition operation on two numerical values within an AJAX function

Hello, I am a beginner in ajax and I am attempting to sum two numbers within an ajax function. Here is the code snippet that I am using: $("#next_btn").click(function(){ Display_Load(); var page = this.title; var subtract = 1; $("#content" ...

Executing Statements in a Specific Order with Express and Sqlite3

I am having an issue creating a table and inserting an item into it using the node command. Despite my efforts to reorganize my script, the item is being inserted before the table is created. Interestingly, manually inputting the commands in sqlite3 works ...

console fails to return a function even when it is defined

After clicking the "stopCrash" button, I want the function backAgain to be executed 2 seconds later. However, I am encountering an error in the console: Uncaught TypeError: this.backAgain is not a function. Do you have any suggestions on how to fix this i ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

The type '{ id: string; }' cannot be assigned to the type 'DeepPartial<T>'

In my code, I am attempting to create a generic function that abstracts my repository infrastructure for creating a where clause. export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export int ...