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

retrieve the value of an HTML element once it has been modified

When I am working in a view, I encounter an issue where I need to retrieve the value of an HTML input box after it has been changed. Initially, the page loads with the following code: <input id="input_one" type="text" value = "apple" /> Upon loadin ...

Invoke a parent method from a nested child component in Vue

After setting up a project with vue-cli using the webpack template, I decided to incorporate a reusable bootstrap modal dialog in the App component. To achieve this, I created a method called showMessage in the App component that handles displaying the mod ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

Enhance the functionality of the kendo grid by incorporating additional buttons or links that appear when the

Is there a method to incorporate links or buttons when hovering over a row in a kendo grid? I've searched through the documentation and looked online, but haven't found a solution. I'm considering if I should modify my row template to displa ...

Console.log() will not display any JSON duplicates

My JSON data structure is pretty flat and can have duplicate attributes. I built a logic to remove the duplicates but when testing it out, something strange happened. The logic was always counting the attributes once, resulting in no duplicates. To test th ...

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

I'm having trouble with my script only fetching the first row of my PHP table. Can someone please take a look at my code

Below is my JavaScript snippet: $('input#name-submit').on('click', function() { var name = $('input#name-submit').val(); if($.trim(name) != ''){ $.post('getmodalreasonUT.php', {name: name}, ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Ways to adjust your selection to the space or new line before or after

$('button').on('click', function(){ const selection = window.getSelection(); selection?.modify('move', 'backward', 'word'); selection?.modify('extend', 'forward', 'to the next space ...

Guide on using react-highlight-words to emphasize various keywords using different color schemes

I am currently working on implementing a search feature for my React project. At the moment, I am only required to enter a single keyword and search for it within the text. Once found, I need to extract and display the sentences containing this keyword sep ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...

Mastering the Material-UI Grid in SPAs: Conquering the Negative Margin Dilemma

While attempting to build a single page application (SPA), I've encountered an issue with using the Grid component from material-ui. Normally, I rely heavily on the Grid, but in this new project, something seems amiss. The current problem is evident ...

What's the best method for uploading a file to AWS S3: POST or PUT requests?

Could you please provide insights on the advantages and disadvantages of utilizing POST versus PUT requests for uploading a file to Amazon Web Services S3? Although I have come across some relevant discussions on platforms like StackOverflow, such as this ...

Incorporate JavaScript strings into HTML dynamically

I am facing some challenges with single quotes while trying to append HTML with a JavaScript string. So far, I have managed to successfully append the element: $("<a class='action-button' id='pl65197buy' value='buy now'&g ...

Execute iMacros Loop and terminate the process before proceeding to the next command

As a newcomer to the world of iMacro scripting, I am struggling with setting up a simple data scrape. I'm looking for guidance on how to create a loop for the following commands: URL GOTO=link1 URL GOTO=link2 URL GOTO=link3 WAIT SECONDS=7.5 Once th ...

Load the dropdown menu in the select element using the AngularJS $ngresource promise

I have a select box on my webpage that I need to fill with data received from a server. I am currently using a service to fetch this data, but I'm unsure how to access the values returned from the promise and populate the ng-options in the select tag. ...

Steps to incorporate this jQuery script

After receiving a solution to my problem, I'm struggling with how to actually put it into practice. $(function(){ $.get('file1.php', function(data){ $('#dropdown1').html( data ); }); // when dropdown1 is chang ...

Triggering Submit Button Based on Checkbox Value in jQuery

Hey there, I'm encountering an issue. Let's say I have two types of checkboxes - one for person and one for company. If I submit the form without checking any of the person or company checkboxes, I want jQuery to display an alert. Otherwise, the ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

When $(.class) displays result, Javascript ceases execution

In the code snippet below, I am trying to load a group of products from a category when the user clicks on the .expandproducts button: $('.expandproducts').click(function(){ id = $(this).attr("data-id"); urlajax = document.location.origi ...