user93796
user93796

Reputation: 18379

JavaScript timeout script

I need a script that I can put on any page in an application and it will run X amount of time. When it hits the amount of time that is specified in the JS it will open either an overlay on the page or a child popup window. Inside either window, I will give you what the text should say.

In the new window, they will have two buttons

resume logout

if they click resume you will kill the overlay or popup window and refresh the parent page. If they click logout you will redirect to a URL.

All of this should be configured in the JS. The overlay window will be simple so I don't need anything complex like jQuery. Just some nice clean OOP JS handmade will be fine.

Upvotes: 1

Views: 3187

Answers (3)

Zed
Zed

Reputation: 57648

<body onload="timerStart()">

...

function timerStart(){
  setTimeout(confirmStay, 60000)   // 1 minute
}

function confirmStay() {
  if (confirm("Press OK to stay here.")) {
    // user pressed OK
    timerStart();   // restart timer
  } else {
    // user pressed Cancel
    location.href="http://example.com";  //redirect to homepage
  }
} 

Upvotes: -1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827198

Yet another approach:

Usage:

var timer = reloadTimer({  seconds:5, logoutURL: '/logout',
                           message:'Do you want to stay logged in?'});
    timer.start();

Implementation:

var reloadTimer = function (options) {
  var seconds = options.seconds || 0,
      logoutURL = options.logoutURL,
      message = options.message;

  this.start = function () {
    setTimeout(function (){
      if ( confirm(message) ) {
        window.location.reload(true);
      } else {
        window.location.href = logoutURL;
      }
    }, seconds * 1000);
  }
  return this;
};

Upvotes: 2

Prestaul
Prestaul

Reputation: 85137

I'm assuming that this has something to do with refreshing a session to preserve a login. If that is the case then you should keep in mind that the user may not respond to your dialog for some time after it pops up. Meaning, your popup may come up after 10 minutes and your session may last for 15 minutes, but if it takes longer than 5 minutes for the user to respond then the session will expire and the refresh of the page will not help you.

<body onload="setTimeout(refreshLogin, 600000)">
    <script>
        function refreshLogin() {
          if (confirm("Press OK to refresh this page and renew your login.")) {
            window.location.reload();   // refresh the page
          } else {
            window.location.href="http://example.com"  //redirect to somewhere
          }
        }
    </script>
</body>

Upvotes: 0

Related Questions