Search code examples
javascripttimercountdown

What's the best way to create a 24 hour countdown that resets once it hits a certain time in the day?


I want to an "order withing x amount of hours for next day delivery". I'm guessing the best way would be JS? but I'm not good at it to pick apart and edit anything I've found so far

My problem is that all of the ones I find are set to specific dates such as June 5th 2018 12:00.

Basically I want it to be set to 17:00 and if it's 15:30, I wan't the timer to say "order withing 1 hours 30 minutes for next day delivery" and then start from 23 hours 59 minutes once the time hits 17:01.


Solution

  • Create a timestamp for arrival and a timestamp based upon the absolute distance to arrival, and use the latter for countdown:

    //Order timestamps
    var arrived = new Date();
    arrived.setHours(15);
    arrived.setMinutes(0);
    arrived.setSeconds(0);
    arrived.setTime(arrived.getTime() + 86400000);
    //Drawing example
    var arriveNode = document.body.appendChild(document.createElement("p"));
    arriveNode.innerHTML = "Arrives in: ";
    var arriveNodeTime = arriveNode.appendChild(document.createElement("b"));
    setInterval(function() {
      var d = new Date(Math.abs(Date.now() - arrived.getTime()));
      arriveNodeTime.innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    }, 100);