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>