Need Help in Countdown Timer


#1

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); 

#2

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.


#4

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.


#5

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


#6

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)

#7

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


#8

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:


Transaction & time counter?
#9

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)

#10

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.


#11

Thanks for Help!

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


#12

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.