Search code examples
javascriptcookiessession-cookies

Uncaught TypeError: Cannot read property '2' of null


I have JS timer that but my cookie script is giving this error:

Uncaught TypeError: Cannot read property '2' of null

The error appears only when reloading the page. So I assume the cookie is there but there is another problem I can't find. The error comes from this line: deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];

Here is HTML

<div id="clockdiv">
I'm a timer
    <span class="days hide"></span>
    <span class="hours hide"></span>
    <span class="minutes"></span> : 
    <span class="seconds"></span>
</div>

Here is JS

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

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

  function updateClock() {
    const 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();
  const timeinterval = setInterval(updateClock, 1000);
}

//const timeInMinutes = 8;
//const currentTime = Date.parse(new Date());
let deadline;

// 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
  deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
} else {
  // otherwise, set a deadline 10 minutes from now and 
  // save it in a cookie with that name

  // create deadline 10 minutes from now
  const timeInMinutes = 8;
  const currentTime = Date.parse(new Date());
  deadline = new Date(currentTime + timeInMinutes*60*1000);

  // store deadline in cookie for future reference
  document.cookie = 'myClock=' + deadline + '; path=/; domain=.codepen.io';
}
initializeClock('clockdiv', deadline);

Solution

  • Try to use ready-made Cookie functions, for ex., from here http://w3schools.com/js/js_cookies.asp

    So

    deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
    

    could be replaced with

    deadline = getCookie('myClock');
    

    Have a look here http://jsfiddle.net/vyspiansky/po2zw4um