Is there a way to ensure that this daily countdown timer continues without resetting at midnight?

Important factors to remember:

This is programmed to imitate the time of 11:00 PM. var bt = "23:00";
This is set to emulate 8:00 AM. var wt = "08:00";

The intended operation:

  • The countdown timer kicks off each morning at 8:00 AM.
  • It counts down until 11:00 PM, every night.
  • At that point, it displays 00:00:00.
  • When morning comes, at 8:00 AM, the countdown restarts once more.
  • This cycle should continue indefinitely.

The current issue:

  • Everything seems functional, except it starts a 24-hour countdown at midnight up until 8:00 AM.

I have attempted to troubleshoot this problem, and my suspicion is that the error lies in how the distance variable is calculated, causing the code to anticipate the next day, but I am unsure how to rectify this.

Here is the link to the Codepen.

and here is the excerpt from my JS script:

$(document).ready(function () {

    var bt = "23:00";  // 11:00 PM
    var wt = "08:00";  // 08:00 AM

    var dateNow = moment().format('MMM D, YYYY');
    placeHolderDate = dateNow + " " + bt;

    var timeNow = moment().format('HH:mm');

    var countDownDate = new Date(placeHolderDate).getTime();

    var countDownHourMin = (wt.split(":"));


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


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

        // Find the distance between now and the count down date
        var distance = countDownDate - now;

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

        $("#countDown").val(hours + ":" + minutes + ":" + seconds);

        // If the countdown is over, write some text
        if (hours === 0 && minutes === 0 && seconds === 0) {
            //clearInterval(x);
            $("#countDown").val("00:00:00");
        }

        if (hours < 0 || minutes < 0 || seconds < 0) {
            //clearInterval(x);
            $("#countDown").val("00:00:00");
        }
        var timeNow = moment().format('HH:mm');
        //console.log('Time Now:' + timeNow);
        //console.log('Wake Time:' + wt);
        if (timeNow === wt) {
            clearInterval(x);
            restartCountdown();
        }


        //console.log(hours + ":" + minutes + ":" + seconds);

    }, 1000);


    function restartCountdown() {
        //log("restartCountdown Started!");

    var bt = "23:00";  // 11:00 PM
    var wt = "08:00";  // 08:00 AM

        var dN = (moment().add(moment.duration({d: 1})).format('MMM D, YYYY'));
        console.log('dn ' + dN);

        var placeHolderDate = dN + " " + bt;
        var countDownDate = new Date(placeHolderDate).getTime();

        var countDownHourMin = (wt.split(":"));


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

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

            // Find the distance between now and the count down date
            var distance = countDownDate - now;

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

            $("#countDown").val(hours + ":" + minutes + ":" + seconds);

            // If the countdown is over, write some text
            if (hours === 0 && minutes === 0 && seconds === 0) {
                //clearInterval(x);
                $("#countDown").val("00:00:00");
            }

            if (hours < 0 || minutes < 0 || seconds < 0) {
                //clearInterval(x);
                $("#countDown").val("00:00:00");
            }

            //  console.log(hours + ":" + minutes + ":" + seconds);

        }, 1000);

    }
});

Answer №1

Your code has been edited and the updated version can be found on this CodePen here. Feel free to optimize the code further as needed. The main concept is to check if the current time falls between 8 AM and 11 PM, displaying the value if true or '00:00:00' if false. Additionally, the dates will update automatically when a new day begins.

$(document).ready(function () {

function countdown() {
     var beginTime = "23:00",  // 11:00 PM
         waitTime = "08:00";  // 08:00 AM

    var today = new Date(),
        dd = today.getDate(),
        mm = today.getMonth()+1,
        yyyy = today.getFullYear();

    var startTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + waitTime),
        endTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + beginTime);

    setInterval(function() {
       var now = new Date();
       var nowdd = today.getDate();
       var nowTime = now.getTime();
      if(dd !== nowdd) {
        dd = nowdd;
        var nowmm = now.getMonth() + 1,
            nowyyyy = now.getFullYear();
        startTime = new Date(dd + '/' + mm + '/' + yyyy + ' ' + waitTime);
        endTime = new Date(dd + '/' + mm + '/' + yyyy + ' ' + beginTime);
      }

      if(nowTime > startTime && nowTime < endTime) {
            var distance = endTime - nowTime;

            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
                minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
                seconds = Math.floor((distance % (1000 * 60)) / 1000);
            $("#countDown").val(hours + ":" + minutes + ":" + seconds);
         } else {
           $("#countDown").val("00:00:00");
         }
    }, 1000);
  }
  countdown();
});

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

Guide on setting a value in $(document).ready using code behind

I am currently working on a .NET application with the use of Twitter Bootstrap. My main challenge right now is retrieving data from a .aspx.cs page to a .aspx page. Here's a look at my code: strObject.cs public class strObject { public string Nam ...

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

Putting Text Inside a Video Player in HTML

Is there a way to insert text, like a Logo, into my video player? I would appreciate any help on how to achieve this. Thank you. <video width="320" height="240" controls src="video/flashtrailer.mp4"> Your browser does not support the video tag. & ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Node.js is essential when using Angular for implementing ui-select components

I'm currently delving into learning AngularJS. I've successfully created a basic web application using AngularJS, with Java EE powering the backend (server side). This app is being hosted on Tomcat. The advantages of AngularJS over JQuery are bec ...

Utilizing react.js and passing props as parameters in recursive functions

When using recursion, I encountered an issue where I am unable to pass the props parameter: class App extends React.Component { constructor(props) { super(props); this.state = { visible: this.props.root, a:this.props.a }; } toggle(){ thi ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

Interested in learning how to filter nested tables?

After successfully integrating a filter code snippet, I encountered an issue with the filter not recognizing data tables that can only be inserted as nested tables. Due to my limited knowledge of JavaScript/CSS, I'm unsure if this problem can be resol ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

Utilizing Selenium WebDriver with Python: Harnessing Test-Created Variables in JavaScript

How can I trigger the variable a, which I set to "Text" for testing purposes? ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Tips for minimizing excessive repetition in your for loops

I'm currently working on developing a Chess game and I've encountered an issue with code redundancy within my Bishop class. My goal is to create a function that can determine all possible moves of a bishop on the board. In order to achieve this, ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

What is the best way to differentiate between two calls to the same method that are based on different arguments?

Currently, I am utilizing sinon to mock functions from Google Drive in my NodeJS project. In a single test scenario, I make two separate calls to the create method (without the ability to restore between calls): // Call 1: drive.files.create({ 'reques ...

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...

Transferring array data between two distinct click actions

Is there a way to transfer values between click events in jQuery? For example, on the first click event I want to add or remove values from an array based on whether a checkbox is checked. Then, on the second click I would like to iterate through all the ...

What could be causing the issue with my css `content:` not functioning across different browsers, and how can I enhance cross-browser compatibility in all cases

Working on my first HTML/CSS project, I encountered a browser compatibility challenge. The code functions well in Firefox, IE, and Edge but fails in Chrome. Specifically, I am trying to make a button display alternating up and down arrows when clicked. Whi ...

Incorporating AngularJS and Bootstrap for seamless pagination experience

My JSON data looks like this: http://localhost:3001/images?page=1 {"images":[{"_id":"542e57a709d2d60000c93953","name":"image1","url":"http://www.syll.com","__v":0},{"_id":"542e58e19d237e5b790f4db2","name":"image154","url":"www.rufyge.com"},{"_id" ...