What is the best way to implement a 5-second delay after the timer reaches 00:00?

I am in the process of creating a countdown timer for an application. Once the timer reaches 00:00, I would like to add a 5-second delay before it starts counting down again. How can I achieve this using setTimeout()?

function initiateTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

           display.textContent = minutes + ":" + seconds;

            if (--timer < 0) {
                timer = duration;
            }
    }, 1000);
    duration = timer;
}

Answer №1

If you want to ensure that only positive numbers are displayed, consider wrapping the line timer = duration; in a function and passing it to setTimeout. This way, the updated time will only be shown if timer >= 0, preventing negative numbers from appearing.

const display = document.querySelector('#display')

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
            if(timer >= 0){
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

           display.textContent = minutes + ":" + seconds;
           }

            if (--timer < 0) {
                
                setTimeout(()=>timer = duration,5000)
            }
    }, 1000);
    duration = timer;
}

startTimer(10,display)
<div id="display"></div>

Answer №2

Keep the interval running until you take action to clear it. When the timer reaches zero, clear the interval and then initiate a timeout to restart it. Remember to store the interval handle in a variable if you want to clear it later. Use recursion for this task:

function startTimer(duration, display) {
  var timer = duration, minutes, seconds;
  var timerInterval = setInterval(function () {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
        window.clearInterval(timerInterval);
        window.setTimeout(() => startTimer(duration, display), 5000);
    }
  }, 1000);
}

Answer №3

Greetings from Stackoverflow! To meet your objective, consider incorporating a secondary timer within your existing code. Here's an example:

function initiateTimer(length, view) {
    var timer = length, minutes, seconds;
    setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

           view.textContent = minutes + ":" + seconds;

            if (--timer < 0) {
                setTimeout(function(){
                    timer = length;
                },5000); // Implement 5-second delay
            }
    }, 1000);
    length = timer;
}

Answer №4

This method does not rely on setTimeout as it is deemed unnecessary. Instead, it simply counts down to -5 (without updating the display) before resetting.

function initiateTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
            if (timer >= 0) {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.textContent = minutes + ":" + seconds;
            }
            
            --timer;
            
            if (timer <= -5) {
                timer = duration;
            }
    }, 1000);
}

window.onload = function() {
  initiateTimer(10, document.getElementById('display'));
};
<span id="display"></span>

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

The autocomplete feature in Atom is not functioning as expected

Autocomplete+ is included with the installation of Atom and is activated by default. I have noticed that when I am coding, no suggestions are appearing. What could be causing this issue? Do I need to adjust any files in order for Autocomplete+ to functio ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

What is the best way to extract a JSON value and use it across multiple functions?

Currently, everything seems to be working fine. However, I'm unsure about the correct way to call the json data. I attempted using a direct link but it didn't work. Do I need to modify the "data" parameters? I'm confused because I saw that ...

Sort the results by total count in Mongoose Express Node.js after grouping by id

I have a unique collection of items: { "_id": { "$oid": "5f54b3333367b91bd09f4485" }, "items": [ { "_id": 20, "name": "Turkish Coffee", "price": ...

Using Angular's ng-repeat prefilter with JavaScript

Is it possible to achieve the functionality of this angular js filter ng-repeat on a tr element using pure javascript? Could it be done in just one custom filter? Please note that showRow is a function that returns a boolean value, and searchString is a s ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading]. This particular ...

Ensure that the nested div maintains its height consistently across all three columns

In my layout, I am trying to achieve uniform height for three columns, each containing the same sections like title and address. Not only do I want the cards to have the same height, but also the nested sections should maintain equal heights. For instance, ...

Utilize jQuery to deactivate all click interactions except for the scrollbar

I am currently working on creating a page that is completely unclickable, both with right and left clicks, and I want to display a message when someone attempts to click. This may lead to some questions such as "Why would anyone want to do this? This s ...

Tips for patiently anticipating an object to undergo asynchronous modifications?

I have an array containing items, and I need to incorporate the asynchronous value from getProductMinQuantity. The issue I'm facing is that the response with res.status(200)... gets sent before modifying item.order_quantity_minimum. I had assumed us ...

Ways to display a different landing page when navigating to the homepage of a website

In the Next application, I have set up a dynamic route at the root of my pages folder as src/pages/[page].js While this works smoothly for pages with slugs like example.com/my-page, it poses a challenge when trying to access a designated slug named homepa ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...

Ordering Algorithm in AJAX Grid

I have a specific requirement that I spotted on this website: Whenever a user clicks on the table header, the content should be sorted accordingly. I have successfully implemented this feature for tables with pre-set values. https://i.sstatic.net/7cebx.p ...

Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code: app.get('/search/:query', (req, res) => { pool.getConnection((err, connection) => { if(err) throw err ...

Automated browsing: identifying the difference between AJAX and iframes

During my automated requests (scheduled at specific times, without user involvement), I have noticed that xmlHttpRequest includes extra http headers. In order for the server not to be able to distinguish these requests as automated (they should appear exa ...

How can you personalize the background color of a Material-UI tooltip?

Is there a way to customize the hover tooltip with a "? icon" for users providing input guidance in a text field? I prefer the design to have white background with grey text and larger font size, as opposed to MUI's default style which is grey with wh ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

Ways to extract a Bearer Token from an Authorization Header using JavaScript (Angular 2/4)

When working with JavaScript, I have successfully implemented a method for authenticating to my server using an http post request. Upon receiving a response from the server, it includes a JWT in an Authorization header like this: Authorization: Bearer my ...

Learn how to toggle between two different image sources with a single click event in JavaScript

If the button is clicked, I want to change the image source to one thing. If it's clicked again, it should change back to what it was before. It's almost like a toggle effect controlled by the button. I've attempted some code that didn&apos ...