Javascript, AJAX, PHP Session Timeout Extension, Bank Timeout

Hello,

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 a reset timer where I have a comment to reset the TIMER HERE. I've tried several 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!

+2


a source to share


2 answers


First of all, you need to use the operator new

in var timer = new reloadTimer

, and also the reloadTimer should be capitalized in ReloadTimer to indicate that it should be used with new

.

The reason you need new

is because the function is being referenced this

, and when used without, new

it will be the global scope, not the instance that it is itself.

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

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

      

UPDATE



In terms of reset is relevant means to restart the timer?

If so, use setInterval

insteadsetTimeout

UPDATE 2

And here's a slightly better fit (if you still want to use a class like this 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();

      

+2


a source


Can you execute the function again with the same parameters?



0


a source







All Articles