Creating a Countdown in Javascript Using a Variable

I want the date to change from the first date to the second date. At the start, it should display 'Starts:' in bold followed by the remaining time. Once it switches to the second date, it should show 'Ends:' in bold and then the remaining time. When both countdown timers reach zero, I would like it to show a message saying the event has ended. Here is my current progress.

<script>
// Set the dates we're counting down to
var countDownDate = new Date("July 23, 2020 21:07:00").getTime();
var countDownDate2 = new Date("July 23, 2020 21:08:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distances between now and the count down dates
  var distance = countDownDate - now;
  var distance2 = countDownDate2 - now;
  var selectedDistance;
  if (distance < 0 && distance2 > 0) {
      selectedDistance = distance2; 
  } else {
    selectedDistance = distance;
  }

  // Calculate days, hours, minutes, and seconds
  var days = Math.floor(selectedDistance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((selectedDistance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((selectedDistance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((selectedDistance % (1000 * 60)) / 1000);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = "Starts: " + days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // Change to the next expiration.
  if (distance < 0 && distance2 > 0) {
   function changeDate() {
   selectedDistance = distance2; 
   }
  }
  
// If the count down is over, show some text 
if (distance2 < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
}}, 1000);
</script>

Answer №1

It appears that you have a good grasp of the concept, assuming I understand the question correctly. Simply introduce another variable for the Start/End label, and then incorporate it when setting the .innerHTML of the demonstration element.

<div id="demo"></div>
<script>
// Define the target date for the countdown
   
//var countDownDate = new Date("July 23, 2020 21:07:00").getTime();
var countDownDate = Date.now() + 5000; // using a shorter time for testing purposes;
// var countDownDate2 = new Date("July 23, 2020 21:08:00").getTime();
var countDownDate2 = Date.now() + 10000;

// Update the countdown every 1 second
var x = setInterval(function() {

  // Get the current date and time
  var now = new Date().getTime();

  // Calculate the difference between the current time and the countdown date
  var distance = countDownDate - now;
  var distance2 = countDownDate2 - now;
  var a;
  var label = 'Starts: ';
if (distance < 0 && distance2 >0) {
    a = distance2;
    label = 'Ends: ';
} else {
    a = distance;
}

  // Perform time calculations for days, hours, minutes, and seconds
  var days = Math.floor(a / (1000 * 60 * 60 * 24));
  var hours = Math.floor((a % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((a % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((a % (1000 * 60)) / 1000);

  // Display the result in an element with id="demo"
  document.getElementById("demo").innerHTML = "<strong>" + label + "</strong>" + days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // Switch to another experiment.
  if (distance < 0 && distance2 > 0) {
   function changeDate() {
   a = distance2; 
   }
  }
  
// If the countdown has ended, display a message 
if (distance2 < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
}}, 1000);
</script>

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

Validating a model in Mongoose: Best practices for updating data

I am facing an issue with my model. It seems that while creating, incorrect information is prohibited, but when editing, it is allowed. How can I prevent this from happening? var userSchema = new Schema({ cartaoCidadao: { type: String, require ...

Obtaining the selected date value from a Vue.js datepicker

How can I calculate the difference in days between two selected dates in Vue.js before the form is submitted? I want to provide a price based on this calculation. I am using a Persian date picker, which you can find here: https://github.com/talkhabi/vue- ...

Updating the positions of Mesh objects in Three.js asynchronously

I'm currently working on a Three.js application where I am creating a grid to display various objects. These objects are rendered on the grid based on their positions, which are obtained from data fetched from a REST API that I poll every 300 millisec ...

Showing the URL beyond the search bar: A Guide using PHP, JavaScript, and HTML

How can I display the URL link outside the search box instead of opening a new page with the search result? I want to show the full URL (https://www.php.net.) below the search box, not within the search results. I only want to see the URL, not the contents ...

Looking to find top-notch keywords that stand out from the rest?

My chosen keyword is s='young girl jumping' function selfreplace(s) { var words = ['man', 'jumping']; var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g&a ...

What drawbacks come with developing an Express.js application using TypeScript?

Curious about the potential drawbacks of using TypeScript to write Express.js applications or APIs instead of JavaScript. ...

What is the best way to increase a numerical input?

While experimenting with HTML input elements, I decided to utilize the step attribute. This allowed me to increment the current value by 100 when clicking the up or down arrows in the input field. However, I discovered that the step attribute restricts th ...

Is it possible to store an HTML element tag in a variable?

I've been learning JavaScript on w3schools and freecodecamp, but I stumbled upon something in w3schools that has me puzzled. Can someone please explain why this particular code snippet works? The variable "text" is declared as containing the string " ...

Disabling dates in the second datetimepicker depending on following days selected in the first one

I have implemented the bootstrap date picker and I am using two textboxes for searching by date range. I want the second textbox to display the days after the date selected in the first textbox. Any suggestions would be appreciated. Here is the HTML code: ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

How to arrange a collection of objects in JavaScript

I am facing a challenge with sorting the array based on the address._id field of each object. Despite attempting to use the lodash orderby function, I have not been able to achieve the desired outcome. [{ rider_ids: '5b7116ea3dead9870b828a1a& ...

In order to manage this file type properly, you might require a suitable loader, such as an arrow function within a React

Currently, I am in the process of creating an npm package and have encountered a difficulty with the following code: You may need an appropriate loader to handle this file type. | } | | holenNummerInSchnur = Schnur => { | if (this.beurte ...

Attempting to determine income in JavaScript with the inclusion of two distinct rates

Trying to come up with a salary calculation for different rates within the same timeframe is proving to be quite challenging. For instance, between 10:00-15:00 the rate is $20 per hour and from 15:00 onwards it drops to $15 per hour. Check out the entire ...

Using JQuery, ensure that the scroll function runs in advance of the ajax call finishing

I am currently working on using jQuery to scroll down to a text box when the click event occurs. However, I have noticed that the scroll event is happening after the AJAX call within the function. $("#execute_btn").click(function(){ $('html, b ...

issue with fetching response from ajax post call in slim framework 3

Update: The issue has been resolved. The correct localhost address for the ajax request should have been 127.0.0.1 instead of 121.0.0.1 On my client side, I am using the following code to send a POST request to localhost/login. <html> <title> ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

I am not encountering any errors; however, upon entering the room, my bot fails to initiate creation of a new channel

const Discord = require("discord.js") const TOKEN = "I forgot to include my token here" const { Client, GatewayIntentBits } = require('discord.js'); const { MemberFetchNonceLength } = require("discord.js/src/errors/Erro ...

Encountered an issue while attempting npm install, with the error message "Error: Undefined variable standalone_static_library in binding.gyp" and node-sass chokidar error

I've been working on updating a Ruby on Rails and React project from 3 years ago. However, I encountered an issue while trying to npm install. $ npm install gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ... This is the error message I&apo ...