Home > Software engineering >  Repeat timer infinite amount of times
Repeat timer infinite amount of times

Time:02-02

I am trying to add a countdown timer to my Shopify checkout using Google Optimize. I got this to work using the following HMTL & JS. Taken from here

However once the timer finishes and I reload the page it starts from 17 seconds instead of 5 minutes.

Is there a way to get this to repeat the timer from 5 minutes once it hits 0?

document.getElementById('timer').innerHTML =
  05   ":"   00;
startTimer();


function startTimer() {
  var presentTime = document.getElementById('timer').innerHTML;
  var timeArray = presentTime.split(/[:] /);
  var m = timeArray[0];
  var s = checkSecond((timeArray[1] - 1));
  if(s==59){m=m-1}
  if(m<0){
    return
  }

  document.getElementById('timer').innerHTML =
    m   ":"   s;
  console.log(m)
  setTimeout(startTimer, 1000);

}

function checkSecond(sec) {
  if (sec < 10 && sec >= 0) {sec = "0"   sec}; // add zero in front of numbers < 10
  if (sec < 0) {sec = "59"};
  return sec;
}
<div>Your cart is reserved for <span id="timer"></span></div>

If you could give the answer like you are talking to a complete beginner it would be greatly appreciated.

Looks like I have a lot to learn!

CodePudding user response:

Welcome to StackOverflow. This should help out...

//JAVASCRIPT
startTimer(5); // SPECIFY AMOUNT OF MINUTES OR NO PARAMETER FOR DEFAULT 5

function startTimer(minutes = 5){
  var timeout = minutes * 60000;
  var ms = timeout;
  var interval = setInterval(function(){
    ms -= 1000;
    if(ms >= 0) {
      var d = new Date(1000*Math.round(ms/1000)); 
      document.getElementById('timer').innerHTML = getMS(d);
    } else {
      startTimer(5); // MAKE TIMER RESTART AGAIN FOR 5 MINS
      // clearInterval(interval); // TO MAKE TIMER STOP UPON REACHING 0:00
    }
  }, 1000);
}

function getMS(d){
  return pad(d.getUTCMinutes())   ':'   pad(d.getUTCSeconds());
}

function pad(i) { 
  return ('0' i).slice(-2); 
}
<!--HTML -->
<body>
<div>Your cart is reserved for <span id="timer"></span></div>
</body>

CodePudding user response:

In javascript the setInterval function allow you to make anything you want every fixed ms.

interval = setInterval(() => {
              console.log('Waited for 5m');
              // Do whatever you want
              console.log('Waiting for 5m again...');
           }, 300000);

// To stop the interval
clearInterval(interval);
  •  Tags:  
  • Related