Instructions on creating a countdown timer that reveals a hidden div once it reaches zero, remains visible for a set period, and then resets

I created a countdown timer that displays a div when the timer reaches zero. However, I am struggling with getting the timer to reset and start counting down again after displaying the div.

For instance, if I set the timer for 7 days and it reaches the deadline, the div should be displayed for 7 days before starting the countdown again for another 7 days.

I can easily implement a basic timer that shows the div when time is up, but I'm unsure how to make it count down again and display the div repeatedly without resetting upon refresh.

Here is my code snippet:

var time = 5;

window.setInterval(test, 1000);

function test() {
    time -= 1;
    $('#test').html(time);

    if (time == 0) {
        $('#test').remove();
        $('#a').show();

    }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test" style="border:1px solid black;width:100px">test

</div>

<div id="a" style="display:none;">
testing
</div>

Answer №1

let remainingTime = 5,        // keep this unchanged!
    counter = remainingTime;  // we'll change this reference instead

window.setInterval(timerFunction, 1000);

function timerFunction() {
  counter -= 1;
  $('#test').html(counter);
  if (counter === 0) {
     counter = remainingTime;  // see?
     // Execute certain actions here.... 
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test" style="border:1px solid black;width:100px">test</div>

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

Explore the world of interior CSS border styles

Trying to achieve a unique border effect like the one shown in the image. Experimented with different styles such as inset, outset, ridge, and groove, but unable to get the desired outcome. Is there a way to create a border that bends inwards towards the m ...

CriOS unable to recognize OPTIONS request from Tomcat 8

My application uses POST requests with CORS for backend services (from www.mydomain.com to api.mydomain.com). The backend is served by a Tomact8 server, implementing a CORSResponseFilter as shown below: public class CORSResponseFilter implements Container ...

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...

Error: The ng-click directive is encountering a parsing syntax error. The token 'Object' is unexpected and is causing the error, it is expected to be enclosed in

When a user clicks on a point on a Google map, I am conducting reverse geocoding in the following manner: geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { ...

Change the DER encoded ANS.1 format of an AWS KMS ECDSA_SHA_256 Signature to JWT base64url encoded R || S format using NodeJS/Javascript

I am currently working on generating a JWT Signature in NodeJS using the ES256 algorithm and AWS KMS Customer Managed Keys. However, I have encountered an issue where the signature created by AWS KMS with ECDSA_SHA_256 cryptographic Signing Algorithms is ...

Problem with (click) event not triggering in innerHtml content in Angular 4

For some reason, my function isn't triggered when I click the <a... tag. Inside my component, I have the following code: public htmlstr: string; public idUser:number; this.idUser = 1; this.htmlstr = `<a (click)="delete(idUser)">${idUser}&l ...

Is there a way to combine all the text on an HTML page into one continuous string without losing the CSS styling?

If I want to change all the text within every HTML element on a page to just the letter "A", how would I do it? Let's say I have a webpage set up like this: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

approach for extracting values from nested objects using specified key

There are objects in my possession that contain various nested objects: let obj = { nestedObject: { key: value } } or let obj2 = { nestedObject2: { nestedObject3: { key2: value2 } } } and so on. Retrieving the values from these objects i ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

Ensuring the proper sequence of operations within a jQuery ajax callback function

I am facing an issue with my jQuery ajax function. The callback function includes two actions: 1) Taking the ajax result (which is an html form) and inserting it as the inner html of an html span. 2) Submitting this form How can I make sure that the form ...

Split your payment in half (50%) by choosing Cash on Delivery with Woocommerce's ajax feature

I'm currently working on implementing an AJAX function that allows users to pay half the total amount when using a custom cash on delivery method. The total amount should change based on whether the user selects yes or no in the radio button. This li ...

Jquery loop using closures

I've been working on creating a plugin that involves passing handler functions for specific events. Consider the scenario below: I have two buttons, and when I click button 1, its label is supposed to change to 'Button A', while clicking but ...

How can I implement a single-column search feature in a GridView using Javascript in ASP.NET?

I found a Google function for client-side searching in a grid using a textbox Here is the function: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function searchFunction(phrase, ...

"The jQuery AJAX function is displaying an error message indicating that the resource was

Does anyone have experience using jQuery AJAX to send data from the client side to the server? I thought it would be straightforward, but I keep getting a "not found" error. Here's the AJAX code I'm using: <script type="text/javascript"> ...

What is the best way to link the width and height of a div with form fields?

I need to implement a feature where I can create multiple div elements that are draggable and resizable, and have their properties like width, height, etc. linked to corresponding objects in an array. For example, if I create six divs, there should be six ...

Error encountered: Firebase cloud function in Node.js V10 has experienced a parsing issue due to an unexpected token 'select

Each time I try to deploy my cloud function, I encounter a Parsing error: Unexpected token selectWinner. I attempted to resolve this by updating the parser options in .eslintrc.json to utilize ecmaVersion 2017, but unfortunately, that did not solve the is ...

How can one retrieve the 'alt' attribute text from an image tag on a webpage using the JSOUP library in an Android application?

Extracting the 'alt' text from an 'img' tag in Android after clicking a button is causing issues. The attempted code is not working as expected. Here is the snippet of the code that was used: Document doc = Jsoup.connect(url).get(); ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...