简体   繁体   中英

Count down timer on multiple pages

I have a timer on the home page. When user makes any action, such as mouse move, the timer will be reseted. When the timer count down to 05:00, system will pop-up a alert to reset timer by clicking "OK". If no action within 5 min and timer count down to 00:00, user forced to log out. My problem is this timer only works within one page, if I have two pages opened, the timer only reset on focused page. I'll still be logged out due to the unfocused page.

Can anyone help me on this? Thanks so much!

<script type="text/javascript">
  var flag = false;
  startTimer();
  function startTimer() {
    var presentTime = $("#Status").text().toString();
    var timeArray = presentTime.split(":");
    var m = timeArray[0];
    var s = checkSecond((timeArray[1] - 1));
    if(s==59) {
      m=m-1;
      if(m < 10) {
        m = "0" + m;
      }
    }

    if (m==05 && s==00) {
      flag = true;
      BootstrapDialog.alert("You have 5 minutes remaining in your session. Click \"OK\" to extend the session.", function() {
        flag = false;
        resetTimer();
      });
    }

    if(!flag) {
      //Reset timer upon user action
      document.onload = resetTimer;
      document.onmousemove = resetTimer;
      document.onmousedown = resetTimer;
      document.ontouchstart = resetTimer;
      document.onclick = resetTimer;
      document.onscroll = resetTimer;
      document.onkeydown = resetTimer;
    }
    else {
      document.onload = null;
      document.onmousemove = null;
      document.onmousedown = null;
      document.ontouchstart = null;
      document.onclick = null;
      document.onscroll = null;
      document.onkeydown = null;
    }

    if (m==0 && s==00) {
      window.location.replace("/Logout");
    };

    setTimeout(startTimer, 1000);
  }

  function checkSecond(sec) {
    if (sec < 10 && sec >= 0) {sec = "0" + sec};
    if (sec < 0) {sec = "59"};
    return sec;
  }

  function resetTimer() {
    $("#Status").html("30:00");
  }
</script>

<div> Your session has <h5 id="Status">30:00</h5> remaining. </div>

your problem is that you want to control two pages by 1 script,but variables in each page is independent.

if you solve this problem you could control your page.

you can get the variable m and s from cookie or localstorage. varibales in cookie and localstorage can be visit in different page if the these pages are in the same root.

try it,just replace the variables.get && set it from cookie or localstorage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM