Need Help in Countdown Timer

After Count down reach zero I reload or refresh page then timer set automatically minus value instead of it’s shows only zeros. And one another question how to set cookie into my timer. Below my code that i used

I also checked example in codepen same issue on codepen ( https://codepen.io/SitePoint/pen/MwNPVq )

function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}

function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');

function updateClock() {
var t = getTimeRemaining(endtime);

daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

if (t.total <= 0) {
clearInterval(timeinterval);
}
}

updateClock();
var timeinterval = setInterval(updateClock, 1000);
}

// if there's a cookie with the name myClock, use that value as the deadline
if(document.cookie && document.cookie.match('myClock')){
// get deadline value from cookie
var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
}

// otherwise, set a deadline 10 minutes from now and 
// save it in a cookie with that name
else{
// create deadline 10 minutes from now
var timeInMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);

// store deadline in cookie for future reference
document.cookie = 'myClock=' + deadline + '; path=/; domain=.[yourdomain.com](http://yourdomain.com/)';
}

var deadline = '2018-10-06 14:52';
initializeClock('clockdiv', deadline); 

Hi @dharminflickdevs, you might either guarantee that the remaining time never has negative values:

function getTimeRemaining (endtime) {
  var t = new Date(endtime) - new Date()
  var seconds = Math.max(0, Math.floor((t / 1000) % 60))
  // etc...
}

Or not start the timer in the first place when the deadline is in the past:

if (new Date(deadline) > new Date()) {
  initializeClock('clockdiv', deadline)
}

The cookie handling in your code works for me, but you’re always overwriting the deadline variable with the string "2018-10-06 14:52" near the end of the code… if you remove that line it should work.

1 Like

Why not run the timer inside a promise, when the timer times out fulfil the promise.
And why use cookies when you can set data attributes on elements.

Thank you so much now timer work nice with cookie time but after i change the timer value from "var timeInMinutes = 10; " it’s give error in “Uncaught TypeError: Cannot read property ‘2’ of null”. error in this code var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
Also When i remove cookie from my browser it’s work perfect but after reach zero i refersh the page it’s give error till the i not clear the cookie from browser or close the browser

Well that means that there is no match, but that shouldn’t have anything to do with the value of timeInMinutes. Try the following for a more robust initialisation though:

function getCurrentDeadline () {
  var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)
  // First check if there is a match at all, and only then
  // return a new date from the captured value
  return deadline && new Date(deadline[2])
}

function initDeadline (initialTimeInMinutes) {
  var deadline = new Date()

  deadline.setMinutes(deadline.getMinutes() + initialTimeInMinutes)
  document.cookie = 'myClock=' + deadline + '; path=/; domain=' + window.location.hostname

  return deadline
}

// Inititalize the clock with the currently stored deadline,
// or with a new deadline with the specified minutes from now
var deadline = getCurrentDeadline() || initDeadline(10)
initializeClock('clockdiv', deadline)
1 Like

Thanks again for help me, now its working nice, but when One more question how i restart coountdown again after 2 minut of expiration.

Your discussions here prompted me to try my hand at building a count-down clock. You might like to look at it on JSFiddle HERE :grin:

2 Likes

after i refresh page or reload the countdown again start from start value instead of contiue with time. countdown work perfect in Private tab(incognito window)
Here my code

function getCurrentDeadline () {
				  var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/);
				  return deadline && new Date(deadline[2]);
				}

				function initDeadline () {
				    var now = new Date();
					 var days = now.setDate(now.getDate() + 0);
					 var hours = now.setHours(now.getHours() + 0);
					 var minuts = now.setMinutes(now.getMinutes() + 5);
					 var seconds = now.setSeconds(now.getSeconds() +0 );
				
					var deadline = new Date(seconds);
				    document.cookie = 'myClock=' + deadline + '; path=/; domain=' + window.location.hostname;
				  return deadline;
				}

				var deadline = getCurrentDeadline() || initDeadline()
				initializeClock('test-countdown', deadline)

Then there’s most likely an old (possibly corrupted) deadline floating around; try clearing the cookies from the browser dev tools. If you want the timer to restart at some point you might also set an appropriate expiration time in the cookie attributes.

Thanks for Help!

How can i restart count down again after 2 minuts of expired?

When you set the cookie expiry to 2 minutes after the deadline, the timer will restart when the user next visits (or refreshes) the page after the specified time; if you also want the timer to restart while the user still is on the page, just set a timeout to reinitialise the deadline and clock after the timer has finished.

Thanks for help me but i still nothing happen after expire 2 minuts
Here is my code :
Please help me in code :

			function initializeClock(id, endtime) {
				var clock = document.getElementById(id);
				var daysSpan = clock.querySelector('.days');
				var hoursSpan = clock.querySelector('.hours');
				var minutesSpan = clock.querySelector('.minutes');
				var secondsSpan = clock.querySelector('.seconds');

				function updateClock() {
					var t = getTimeRemaining(endtime);
					daysSpan.innerHTML = t.days;
					hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
					minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
					secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

					if ( t.total <= 0 ) {
					  clearInterval( timeinterval );
				
						var timeInMinutes = 2;
						var newdeadline = new Date(deadline + timeInMinutes*60*1000);
						document.cookie = "myClock=; expires="+newdeadline+";
					}
		
				}
		
				updateClock();
				    var timeinterval = setInterval(updateClock, 1000);
			}

There is a syntax error in your code, there’s a quote missing in the cookie assignment (also you can actually just set the expiry when you are creating the cookie). But if you want the timer to restart directly you’ll have to set a timeout:

window.setTimeout(function () {
  initializeClock('clockdiv', initDeadline(10))
}, 2 * 60 * 1000)

Thanks you so much for help me, I was facing one issue during testing time. when i change my value from my code. countdown continue with time that i change instead of it’s show zero. and on reload page it’s continue with start time every time of reload or refresh page. When i clear cookie it’s work nice but after i login into my site and refres page countdown every time on page refree start from start value.

     function getCurrentDeadline () {
	   var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/);
	   return deadline && new Date(deadline[2]);
    }
   function initDeadline () {
		var now = new Date();
		var days = now.setDate(now.getDate() + 0);
		 var hours = now.setHours(now.getHours() + 1);
		var minuts = now.setMinutes(now.getMinutes() + 20);
		var seconds = now.setSeconds(now.getSeconds() +40);
		 var deadline = new Date(seconds);
					
	    document.cookie = 'myClock=' + deadline + '; path=/; domain=' + window.location.hostname;
				  return deadline;
				}
				var deadline = getCurrentDeadline() || initDeadline();
				initializeClock('test-countdown', deadline); 

Try this

<script>
var x = setInterval(function() {

  var t = Date.parse('<?php echo $expire2; ?>') - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  
  
 document.getElementById("<?php echo $did; ?>").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
   if (t < 0) {
    clearInterval(x);
    document.getElementById("<?php echo $did; ?>").innerHTML = "EXPIRED";
 }
}, 1000);
</script>

Thanks for reply but i set my timer time into cookie. it’s work perfect on private tab even when i clear cookie it’s work perfect on front end al;so but login into my site when i reload page every time timer start from start value. So can please help into my code thay given in above msg

I just put together your latest pieces of code and it works fine for me on localhost. Did you try inspecting the cookies in the dev tools? Is the cookie actually getting set? Also (sorry but I have to ask), are cookies enabled in your regular browser profile?

Thanks bro it’s my mistake now it work fine after reac zero.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.