Disable the setTimeout() function in order to prevent the countdown from refreshing

I have a JavaScript countdown function that is working well, but I am unsure how to stop and refresh the timer to extend the time. When I call the function again before it times out, it behaves strangely by showing two countdown timers because the updateTimer() function is still active. After searching online, I came across the clearTimeout() function as a solution to stop this issue, but I don't know how to implement it in this function.

Can someone please assist me in stopping and refreshing this timer?

function countdown(elementName, minutes, seconds) {
    var element, endTime, hours, mins, msLeft, time;

    function twoDigits(n) {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer() {
        msLeft = endTime - (+new Date);
        if (msLeft < 1000) {
            element.innerHTML = "00:00";
        } else {
            time = new Date(msLeft);
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = twoDigits(time.getUTCMinutes()) + ':' + twoDigits(time.getUTCSeconds());
            setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
        }
    }

    element = document.getElementById(elementName);
    endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
    updateTimer();

    return stopTimer();
}

countdown("countdown", 0, 30);

Answer №1

Make sure to assign your setTimeout() to a variable. You won't be able to clear anonymous timeouts.

var timeout;

function timerCountdown(elementName, minutes, seconds) {
    var element, endTime, hours, mins, msLeft, time;

    function twoDigits(n) {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer() {
        msLeft = endTime - (+new Date);
        if (msLeft < 1000) {
            element.innerHTML = "00:00";
        } else {
            time = new Date(msLeft);
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = twoDigits(time.getUTCMinutes()) + ':' + twoDigits(time.getUTCSeconds());
            timeout = setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
        }
    }

    element = document.getElementById(elementName);
    endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
    updateTimer();

    stopCountdown();
}

function stopCountdown() {
  clearTimeout(timeout);
}

timerCountdown("countdown", 0, 30);

Answer №2

To ensure the timer stops at the specified time, you must assign the value returned by setTimeout(...) to a global variable and then use this global variable as an argument for the clearTimeout() function.
To implement this, follow these steps:

let timer;


function countdown(elementID, minutes, seconds) {
    var element, endTime, hours, mins, msLeft, currentTime;
    


    function addLeadingZero(n) {
        return (n <= 9 ? "0" + n : n);
    }

    function stopTimer(timeVar) {
        return clearTimeout(timeVar);
    }

    function updateTimer() {
        msLeft = endTime - (+new Date);
        if (msLeft < 1000) {
            element.innerHTML = "00:00";
        } else {
            currentTime = new Date(msLeft);
            hours = currentTime.getUTCHours();
            mins = currentTime.getUTCMinutes();
            element.innerHTML = addLeadingZero(currentTime.getUTCMinutes()) + ':' + addLeadingZero(currentTime.getUTCSeconds());
            timer = setTimeout(updateTimer, currentTime.getUTCMilliseconds() + 500);
        }
    }

    element = document.getElementById(elementID);
    endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
    updateTimer();

    return stopTimer(timer);
}

countdown("countdown", 0, 30);

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

`Populating fields in Firebase``

I am currently in the process of transitioning from a Mongoose + Express app to using Firebase + Express. However, I am facing some challenges with populating related fields similar to how it is done in Mongoose. Is there a more efficient way to achieve th ...

Creating a textbox with pre-filled content

Seeking assistance with a Java compiler app I am developing through phonegap. Need help setting the default Java Class name in a textarea without it disappearing. This is what I have: <div> <label for="source">Source Code:</label> ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...

Redirecting in AngularJS after a successful login操作

Is there a way to redirect users back to the original page after they login? For example, if a user is on a post like www.example.com/post/435 and needs to log in to "like/comment" on the post, how can I automatically redirect them back to that specific po ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

Navigating Pre-Fetched Client Routes in Gatsby with @ReachRouter

Let's consider this scenario. Imagine a user enters /company/<company-id> in the address bar. Because the app is completely separate from the backend, it must prefetch the companies. The usual flow is /login -> /company/. Handling this sequ ...

Tips for creating a console.log wrapper specifically designed for Angular2 using Typescript

Is there a way to create a custom global logging function in Angular 2 TypeScript project that can be used instead of console.log for services and components? I envision the function looking like this: mylogger.ts function mylogger(msg){ console.log ...

The initial $http POST in Angular ends up hitting the error path within the .then function despite the successful execution of the

Something strange is happening to me. This peculiar behavior occurs only on the initial POST request. However, when I resubmit the form, the subsequent requests work perfectly fine. The first $http post call leads to the error function in .then, even thou ...

Exploring the data-* attribute in jQuery

Currently, I have a form structured as follows: <div data-role="page" data-last-value="43" data-hidden="true" data-bind='attr : {"name":"John"}'></div> My objective is to modify the name attribute from "John" to "Johnny". I am att ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

Does the modularization of code impact the performance of the react-app?

The client provided me with a React app that includes an index.jsx file where 90% of the coding has been completed. To prevent getting stuck in Scroll Limbo, I have started breaking down the code into modules for each specific requirement. These include ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

Interpret data from an external JSON file into a HighCharts chart using JavaScript

Currently, I am exploring the process of incorporating HighCharts Chart data directly within the actual webpage. Below is the complete code snippet: <!DOCTYPE html> <html><head> <script type="text/javascript" src="http://code.jquery. ...

Child components are not able to access properties from the root component in VUE3

Hi there! I'm currently learning VUE3 and had a question about defining global properties in the Root Component. I did some research on Google before posting this question, but couldn't find any relevant results. I would like to set a global pro ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

JavaScript - The left dropdown menu stubbornly remains visible when clicked in white space, unlike the right dropdown which disappears as expected. Puzzled by this inconsistency

Whenever I click on the selection criteria box, a dropdown menu appears. Clicking on the white space or the data table button makes the drop-down menu disappear, which is good. However, when I perform the same action for 'choose data table,' the ...

Is it acceptable for a video to autoplay even if it is not connected to the DOM?

Consider the following three scenarios: document.adoptNode, document.importNode, and document.createElement with assigned properties. In all cases, the video autoplay feature is activated even when it's not connected to the DOM. This behavior diffe ...

Is it possible to customize the color of icons in react's Material-table?

I'm currently utilizing the material-table library and I'm struggling to individually change the color of each icon. Could you assist me with this? I attempted custom CSS, but it's affecting all icons at once instead of specific ones. Here i ...