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!
First of all, you need to use the
newoperator invar timer = new reloadTimer, and also reloadTimer should be capitalized into ReloadTimer to signify that it needs to be used withnew.The reason why you need
newis because the function referencesthisand when used withoutnewthis 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
UPDATE
By RESET do you actally mean to restart the timer?
If so, just use
setIntervalinstead ofsetTimeoutUPDATE 2
And here is a slightly better approach (if you still want to use such a class to encapsulate something so trivial)