0

I am constructing a session timeout as part of a web application using the MomentJS library. What I have so far (below) is the timeToExpire difference (in seconds) from when the user logged in and when the session will expire. However when displaying a countdown clock using setInterval, the diff is NOT recalculated each second and instead the clock is never updated.

Could someone point me in the right direction to what is going wrong?

const access_ttl = 3600;

const now = moment();

const login_timestamp = moment('2017-02-19 17:31:58+00:00');
const expire_timestamp = login_timestamp.add(access_ttl, 's');

const timeToExpire = expire_timestamp.diff(now, 'seconds');

function displayClock(inputSeconds) {
  const sec_num = parseInt(inputSeconds.toString(), 10);
  const hours = Math.floor(sec_num / 3600);
  const minutes = Math.floor((sec_num - (hours * 3600)) / 60);
  const seconds = sec_num - (hours * 3600) - (minutes * 60);
  let hoursString = '';
  let minutesString = '';
  let secondsString = '';
  hoursString = (hours < 10) ? "0" + hours : hours.toString();
  minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
  secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
  return hoursString + ':' + minutesString + ':' + secondsString;
}

function timer() {
  $('.output').html(`Expires in: ${displayClock(timeToExpire)}`)
}

setInterval(timer, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

<div class="output"></div>
stackunderflow
  • 1,644
  • 6
  • 24
  • 40
  • There are very much simpler countdown timers, e.g. [*The simplest possible JavaScript countdown timer?*](http://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer). Note that *setInterval* does not run at exactly the specified delay, so your clock will slowly drift and appear to skip a second from time to time. – RobG Feb 19 '17 at 22:49

1 Answers1

2

You are not updating the now() or timeToExpire values and so the value you are passing to displayClock is always the same.

Link to complete JS Fiddle: https://jsfiddle.net/xzyjdb1g/2/

var now, timeToExpire;

function updateTime() {

  now = moment();

  timeToExpire = expire_timestamp.diff(now, 'seconds');
}

function timer() {
    updateTime();
  $('.output').html(`Expires in: ${displayClock(timeToExpire)}`)
}
Paul Thomas
  • 2,756
  • 2
  • 16
  • 28