Show the present time pulled from the timer

I am in possession of a countdown timer that starts at zero and counts up to 100. The timer displays the count in a p tag with the ID of countdowntimer.

I am attempting to show the current time when I click a button while the timer is running.

Additionally, I would like to reset the timer after clicking the button.

Do you have any suggestions on how I can accomplish this task?

var timeleft = 1;
    var downloadTimer = setInterval(function(){
    timeleft++;
    document.getElementById("countdowntimer").textContent = timeleft;
    if(timeleft >= 100)
        clearInterval(downloadTimer);
    },1000);
    
    
    function timenow()
{
var timenow=document.getElementById("timetaken").textContent = timeleft;

}
<p> Time   <span id="countdowntimer">0 </span></p>
<p> Time  Taken  <span id="timetaken">0 </span></p>
<button onclick="timenow">Click to view time taken</button>

Answer №1

Ensure that your onclick function event is properly bound. To reset the timer, simply set the timeleft variable to 0 within the button click function

var timeleft = 1;
    var downloadTimer = setInterval(function(){
    timeleft++;
    document.getElementById("countdowntimer").textContent = timeleft;
    if(timeleft >= 100)
        clearInterval(downloadTimer);
    },1000);
    
    
    
    function timenow()
{
  document.getElementById("timetaken").textContent = timeleft;
  timeleft=0;
  document.getElementById("countdowntimer").textContent = timeleft;
}
<p> Time   <span id="countdowntimer">0 </span></p>
<p> Time  Taken  <span id="timetaken">0 </span></p>
<button onclick="timenow()">Click to viw time taken</button>

Answer №2

To start, it is important to trigger the function on the onclick event. Additionally, ensure that you reset the timeleft value within that function.

Your revised code should resemble the following:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <p> Time <span id="countdowntimer">0 </span></p>
    <p> Time Taken <span id="timetaken">0 </span></p>
    <button onclick="timenow()">Click to view time taken</button> <!-- Updated timenow to timenow() -->

    <script>
        var sum = 0;
        var timeleft = 1;
        var downloadTimer = setInterval(function () {
            timeleft++;
            document.getElementById("countdowntimer").textContent = timeleft;
            if (timeleft >= 100)
                clearInterval(downloadTimer);
        }, 1000);



        function timenow() {
            sum += timeleft;
            var timenow = document.getElementById("timetaken").textContent = sum;
            timeleft = 0;
            document.getElementById("countdowntimer").textContent = timeleft;
        }   
    </script>
</body>

</html>

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

In Internet Explorer 7, a newline within a <pre> tag may cause display issues

Within my ASP.NET MVC 3 project, I am working with the following code: <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" ty ...

What is the best way to retrieve the index of the chosen option from a select element in Angular when

My Angular application includes a simple <select> element using Material design: <mat-form-field> <mat-label>Type</mat-label> <mat-select placeholder="Type" formControlName="type" name="type" id="name"> <mat-option ...

What is the best way to ensure all my borders are uniform in size?

As I work on a JavaScript project that organizes words into blocks based on their size, I encountered an issue with inconsistent border thickness in certain areas. I'm using spans to contain each word, but I can't figure out how to make the borde ...

Leverage the power of dynamic PHP variables within your JavaScript code

I have an image database and a search form. I want to display the images on the next page using JavaScript with the OpenLayers library. Here is the PHP code I wrote: <?php mysql_connect('localhost','root',""); mysql_select_ ...

Unable to get jQuery plugin to function properly within a .vue component

I am currently working on a Vue component for my Laravel 5.3 application. I am trying to integrate the Laravel File Manager into a standalone button, but it seems like it's not functioning properly. When I click on the button to choose an image, nothi ...

Adding dynamic values to nested form groups in Angular Form Array

After following a tutorial on creating a reactive form in an Angular application, I managed to implement it successfully. However, I encountered an issue when trying to add an additional control called "setNumber" to the form array. I want this control to ...

Can you explain how to break down secured routes, users, and posts all within a single .create() function in Mongoose/JavaScript

I am seeking guidance on utilizing the .create() method within a protected route while implementing deconstructed JavaScript. In the absence of the protected route, I can deconstruct my schema and utilize req.body in .create(...) as shown below. const { ti ...

What is the best way to establish a connection between two applications using React and Node

Currently, I am facing a challenge with integrating two separate applications. One is a login/registration form written in Node.js, Express.js, React.js, and MySQL. The file structure looks like this: https://i.sstatic.net/th6Ej.png The other application ...

steps for setting up socket.io client

Would it be possible to reference the socket.io client library using a relative path like: src="/socket.io/socket.io.js" instead of the absolute path: src="https://miweb:6969/socket.io/socket.io.js" To establish a connection with the library, typically ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Sorting custom strings in Javascript with special characters like dash (-) and underscore (_)

I am attempting to create a custom sorting method with the following order: special character ( - first, _ last) digit alphabets For instance, when sorting the array below var words = ['MBC-PEP-1', 'MBC-PEP01', 'MBC-PEP91&apo ...

Issue with Nextjs: getServerSideProps causing a blank page to display instead of redirecting to 404errorCode

I am facing an issue on my dynamic page where the external server returns a 404 error if the requested product is not found. However, when using getServerSideProps, instead of redirecting to a 404 page, it shows a blank page. Below is the code snippet: // ...

Gesture scrolling transferred to elements under the currently scrolled element

One of the elements on my page is a list that scrolls vertically, named scroll-list-one, and it functions perfectly. Another element, which contains a vertical scrolling list called scroll-list-two, occasionally appears as a popover over scroll-div-one. T ...

working with css to rearrange 3 divs

I am trying to rearrange the positioning of two divs within my HTML code: <div>container <div> Navigation backwards </div> <div> Social buttons </div> <div> Navigation forwards </div> </div> This setup disp ...

Struggling to make a div appear right at the top of the page

Struggling with a basic CSS problem as I practice my skills, I am finding it challenging to position a div at the very top of the screen. Despite setting the background-color, the div is not aligning perfectly with the top edge. Interestingly, adding a bor ...

Are there any methods to create a profile page that adjusts to different screens, such as mobile and desktop, ensuring a seamless user

After successfully installing WordPress on my server, I am pleased with how it looks. However, I am now searching for a profile/front page design that will be responsive and visually appealing on all devices - from phones and tablets to desktops. Despite ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

What could be causing the HTML content to not display when the code is executed?

I've recently started using Visual Studio Code for my project. I am able to build my code without any errors, but when I run it, the HTML content does not display properly - only the CSS styling for the header and footer is visible. I have tried click ...

Merging audio files using Node Stream

Currently facing an issue with joining 2 .wav files together, as my output file only contains the first item in the array: const writeStream = fs.createWriteStream('server/playback.wav'); const inputFiles = [ `${path.resolve(__dirname, 'r ...

Retrieve JSON data from the AJAX event's onreadystatechange function

I'm trying to retrieve a JSON object called "encuesta" from an AJAX request and store it in the global variable "jacu." Here's my code: window.onload = function() { tabla = document.getElementById("pregunta"); jencu = ajax("GET", "datos ...