Obtaining data from event listener during interval execution

I recently developed a countdown timer using JavaScript and included an event listener for a stop button to pause the timer

When I stopped the timer, every second was being logged individually but I wanted to only retrieve the final time value. For example, if the start time was 59:00 minutes and the stop time was 50:15 minutes, I only wanted to display the stop time of 50:15 minutes.

Please see the code snippet below:

    function getTimeRemaining(endtime) {
        const total = Date.parse(endtime) - Date.parse(new Date());
        const seconds = Math.floor((total / 1000) % 60);
        const minutes = Math.floor((total / 1000 / 60) % 60);
        const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
        const days = Math.floor(total / (1000 * 60 * 60 * 24));
        return {
            total,
            days,
            hours,
            minutes,
            seconds
        };
    
    }
    
    function initializeClock(id, endtime) {
        const clock = document.getElementById(id);
        const daysSpan = clock.querySelector('.days');
        const hoursSpan = clock.querySelector('.hours');
        const minutesSpan = clock.querySelector('.minutes');
        const secondsSpan = clock.querySelector('.seconds');
    
        /* buttons */
        const startbutton = document.getElementById('Startbtn')
        const stopbtton = document.getElementById('Stopbtn');
    
        function updateClock() {
            const t = getTimeRemaining(endtime);
    
            daysSpan.innerHTML = t.days;
            hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
            minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
            secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
    
            if (t.total <= 0) {
                clearInterval(timeinterval);
            } else {
                stopbtton.addEventListener('click', (e) => {
                    clearInterval(timeinterval);
                    var StopTime = t.minutes + ":" + t.seconds;
                    console.log(StopTime); // returned as a single item
                })
            }
        }
        // updateClock();
        const timeinterval = setInterval(updateClock, 1000);
    
    }
    
    const deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
    
    initializeClock('clockdiv', deadline);

How can I ensure that only the last stop time value is displayed instead of each individual second?

Your help is greatly appreciated!

Answer №1

It's important to move the event listener outside of the interval and run it only once, as adding it on each iteration can cause unexpected behavior.

Consider implementing the following changes:

const timeinterval = setInterval(updateClock, 1000);

stopbtton.addEventListener('click', (e) => {
    const t = getTimeRemaining(endtime);
    clearInterval(timeinterval);
    const StopTime = t.minutes + ":" + t.seconds;
    console.log(StopTime); /* printed for a single item */
})
Full code snippet:

/* Your JavaScript functions here */

    function initializeClock(id, endtime) {
        /* Function implementation here */

        function updateClock() {
            /* Update clock logic implemented here */
        }

        // Perform additional setup
        
    }

    /* Additional code goes here */


    initializeClock('clockdiv', deadline);
/* Your CSS styles here */

body {
    /* CSS Body styling */
}

h1 {
    /* Heading styles */
}

/* Additional CSS classes go here */

#ConferenceMinutes {
    /* Conference minutes animation style */
}

@keyframes TimerBlink {
    /* Keyframes for timer blinking animation */
}
<!-- HTML markup and script files included here -->

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>

<body>
    <h1>Countdown Clock</h1>
    <div id="clockdiv">
        <div>
            <span class="days"></span>
            <div class="smalltext">Days</div>
        </div>
        <div>
            <span class="hours"></span>
            <div class="smalltext">Hours</div>
        </div>
        <div>
            <span id="ConferenceMinutes" class="minutes"></span>
            <div class="smalltext">Minutes</div>
        </div>
        <div>
            <span class="seconds"></span>
            <div class="smalltext">Seconds</div>
        </div>
    </div>
    <div>
       
        <button id="Stopbtn">StopTime</button>
        
    </div>

</body>
<script src="./app.js"></script>

</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

Managing arrayBuffer in hapi.js: A Comprehensive Guide

I am struggling to upload an arrayBuffer to my server and save it to a file. On the client side, I am using axios, and on the server side, I have implemented Hapi js. However, I am facing difficulties in extracting data from the request in the Hapi handler ...

A quick guide on updating table values in Laravel framework without the use of forms or JavaScript

Currently, I am immersed in my project where I need to fetch data from a table named 'Clients' in a database and exhibit it. Initially, this was quite straightforward. However, I now wish to modify certain information in the table. The challenge ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

I encountered a blank page issue when incorporating ui.bootstrap into my controller within Angular

After attempting to utilize angular bootstrap in my project, I encountered an issue where adding the dependency in my controller and starting the server with grunt serve resulted in a blank page. Take a look at the bower components in the screenshot provid ...

Troubles with modifying website background using JavaScript

I'm looking to update my website background using JavaScript, starting with buttons before moving to a drop-down menu. I have the following code that successfully changes the background when the button is clicked: function selectText(test){ var a ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

Communicating with Controllers: Troubleshooting Module Issues in Angular JS

Currently, I am in the process of learning Angular through this informative video: http://www.youtube.com/watch?v=LJmZaxuxlRc&feature=share&list=PLP6DbQBkn9ymGQh2qpk9ImLHdSH5T7yw7 The main objective of the tutorial is to create a rollover effect ...

Nextjs: utilizing static class or employing a use function

Exploring Methods to Create a Tools Class/Function in NextJS I am considering two different approaches for this task. Using Static Class: class Tools { static titleCase(value: string) { return value.charAt(0).toUpperCase() + value.slice(1). ...

Within Blade, Laravel and Vue components are able to communicate by sharing data from one component to another

Is it possible to achieve this task? Here is the scenario: I have a left navbar displaying membership status (active/inactive). Once the payment gateway receives the payment, a webhook is triggered via Paddle(Laravel Paddle API). During the webhook proc ...

JavaScript's `setAttribute` function appears to be malfunctioning when used in conjunction

I am currently working in ORMB and have come across an input element that looks like this <input id="charVal" class="oraInput" oraField="charVal"> I've been trying to dynamically add an oraSearch attribute using JavaScript, but it doesn't ...

Creating a URL using Form Fields with Javascript or jQuery - Reg

Creating a Custom URL with Form Fields using JavaScript or jQuery I am looking to generate an external link by incorporating a form with a dynamic variable as shown below: (Where 2500 can be customized based on user input) The final URL will be display ...

The JSON response is returning an undefined value

While working on my react app, I am logging JSON data from the backend of the application. When I log the main body of the data: console.log('........section2', options2ndSection[2]); The returned JSON data is as follows: Object item: ...

Exploring Angular2: A Guide to Interpolating Expressions in Templates

Is it possible to interpolate different types of Javascript expressions? Along with displayed properties like object.property and short expressions such as {{1+1}}, what other valid Javascript expressions can be used for interpolation? ...

Encountering issues with Windows 8 PhoneGap FileTransfer when trying to transfer text files

I'm facing an issue while attempting to upload a file to a server - the process seems successful, but the file doesn't actually transfer. I've temporarily hard-coded some values, but here's the code snippet: var options = new FileUplo ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

Utilizing Three.js to instantiate a variety of objects and interact with each one separately

Recently, I managed to create a cube in 'three.js', and now I'm looking to replicate that cube three more times and animate them individually using 'Tweenmax'. As a newcomer to three.js, I would greatly appreciate any guidance or ...

"An issue with the setTimeout function in React is leading to the page constantly refreshing

My buddies and I are in the process of developing a React App. The main goal is to identify the currently logged-in user, then send a post request to fetch everyone in the same "room" as them and display this information on the app upon page load. However, ...

Guide to testing Higher Order Components with React Testing Library

I've created a higher-order component (HOC) that adds props to a component for handling network requests and passing down data as props. Below is a simplified version of the HOC: export const withTags = (Component) => { class WithTags extends Pur ...

Encountering internal server error while utilizing multipart/form-data with Express and KrakenJS

I am facing a challenge with executing a post request using multipart/form-data. Every post request I make results in an Error: Forbidden. The console output is as follows: Error: Forbidden 127.0.0.1 - - [Sat, 12 Apr 2014 20:08:33 GMT] "POST /addComic HTT ...