与差异的MomentJS倒计时

时间:2017-02-19 17:58:50

标签: javascript date datetime momentjs setinterval

我正在使用MomentJS库构建会话超时作为Web应用程序的一部分。到目前为止(下面)我是从用户登录和会话到期时的timeToExpire差异(以秒为单位)。但是,当使用setInterval显示倒计时时钟时,diff每秒都会重新计算 NOT ,而不会更新时钟。

有人能指出我正确的方向出错吗?

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>

1 个答案:

答案 0 :(得分:2)

您没有更新now()或timeToExpire值,因此传递给displayClock的值始终相同。

链接到完整的JS小提琴: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)}`)
}