Some User
Some User

Reputation: 53

Javascript, AJAX, Extend PHP Session Timeout, Bank Timeout

Greetings,

I have the following JS code:

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

  this.start = function () {
    setTimeout(function (){
      if ( confirm(message) ) {
        // RESET TIMER HERE
        $.get("renewSession.php"); 

      } else {
        window.location.href = logoutURL;
      }
    }, seconds * 1000);
  }

  return this;
};

And I would like to have the timer reset where I have the comment for RESET TIMER HERE. I have tried a few different things to no avail. Also the code calling this block is the following:

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

The code may look familiar as I found it on SO :-)

Thanks!

Upvotes: 2

Views: 1716

Answers (2)

Sean Kinsey
Sean Kinsey

Reputation: 38046

First of all, you need to use the new operator in var timer = new reloadTimer, and also reloadTimer should be capitalized into ReloadTimer to signify that it needs to be used with new.

The reason why you need new is because the function references this and when used without new this will be the global scope instead of the instance it self.

To reset a timer you just call window.clearTimeout with the timers reference as the parameter

var timer = window.setTimeout(....
...
window.clearTimeout(timer);

UPDATE

By RESET do you actally mean to restart the timer?

If so, just use setInterval instead of setTimeout

UPDATE 2

And here is a slightly better approach (if you still want to use such a class to encapsulate something so trivial)

var ReloadTimer = function(options){
    var seconds = options.seconds || 0, logoutURL = options.logoutURL, message = options.message;
    var timer;
    return {
        start: function(){
            timer = setInterval(function(){
                if (confirm(message)) {
                    $.get("renewSession.php");
                }
                else {
                    clearInterval(timer);
                    window.location.href = logoutURL;
                }
            }, seconds * 1000);
        }
    };
};
var myTimer = new ReloadTimer({
    seconds: 20,
    logoutURL: 'logout.php',
    message: 'Do you want to stay logged in?'
});
myTimer.start();

Upvotes: 2

stagas
stagas

Reputation: 4793

You could execute the function again with the same parameters?

Upvotes: 0

Related Questions