Search code examples
javascripttimercountdown

Timer every hour but starting from 1 minute


I would like to create a countdown timer for my resource. An example for this I took from Quasimodo's clone answer of this page.

From the code, I took some elements, since I only need minutes and seconds. And I don't need a 30 minute mark.

The code works great, but unlike the author of the question, I need the start to start and end at 1 minute of the next hour.

The changes that I made did not lead to the desired result:

secsRemaining = 3600 - (time.getUTCMinutes()+1)%60 * 60 - time.getUTCSeconds(),

and

mins = (Math.floor(secsRemaining / 60)+60),

This gave a result, but not the one that is needed. When the time on the clock becomes 00 minutes, then the code becomes 60 minutes and 00+ seconds. I need, for example, at 14:00:59 the timer has the values ​​00:01, and when 14:01:01 the timer has the values ​​59:59.

Please let me know how it can be changed to achieve the desired result. Perhaps you have a link to solutions. I couldn't find it on the Internet.

Code I am using:

var byId = document.getElementById.bind(document);

function updateTime() {
  var time = new Date(),
    secsRemaining = 3600 - (time.getUTCMinutes()) % 60 * 60 - time.getUTCSeconds(),
    mins = (Math.floor(secsRemaining / 60)),
    secs = secsRemaining % 60;
  byId('min-part').textContent = mins;
  byId('sec-part').textContent = secs;
  setTimeout(updateTime, 1000 - (new Date()).getUTCMilliseconds()).toLocaleString();
}
updateTime();
<div>Time left before update: <span id="min-part"></span>:<span id="sec-part"></span></div>


Solution

  • Here is how I would do it

    • Generating a date at the next hour and 1 minutes
    • Calculating the number of millisecond between the current date and the next date
    • Display the time remaining

    const minutes = document.getElementById('minutes')
    const seconds = document.getElementById('seconds')
    
    setInterval(() => {
      const now = new Date()
      const nextHours = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 1)
      const nbMilisec = (nextHours - now)
    
      const nbMinutes = parseInt((nbMilisec / 1000 / 60) % 60)
      const nbSeconds = parseInt((nbMilisec / 1000)  % 60)
      
      
      minutes.innerHTML = String(nbMinutes).padStart(2, '0')
      seconds.innerHTML = String(nbSeconds).padStart(2, '0')
    }, 1000)
    <div id="time">
      Time left before update : <span id="minutes"></span> : <span id="seconds"></span>
    </div>