Instead of doing this with one single timer running 15 minutes, how about setting the interval to 1 minute and in the event count down a counter?
This counter could be easily reset by other events, e.g. AJAX calls, click events etc. which can be easily be triggered in jQuery bv .delegate
or .on
methods.
If no such resets occur, the count down reaches 0 and you can do the redirect.
var inactivityCountdown = 15;
intervalid = window.setInterval(function Redirect()
{
inactivityCountdown--;
if (inactivityCountdown<1) {
clearInterval(intervalid);
alert('Your session has been expired and system redirects to login page now.!\n\n');
window.location.href='../index.aspx';
}
}, 60*1000);
You can see, this way it is easy to reset the counter inactivityCountdown
any time before it expires. Don't forget to clear the interval when you do the redirect.
In the following snippet, I am using 10 seconds instead of minutes for better testing. Type something into the text field or click the button to reset the countdown.
You will get the message and then a logout text where you'll be able to login again via a link (this simulates the redirect):
var initCountdownValue = 10;
var inactivityCountdown = initCountdownValue;
$(document).ready(function() {
$(document).delegate("#login", "click", function(e) {
location.reload();
});
function Logout() {
document.getElementById('mainpage').style.display = "none";
document.getElementById('loggedout').style.display = "";
// or window.location.href="/logout.aspx";
}
var intervalid = window.setInterval(function Redirect() {
inactivityCountdown--;
$("#counter").text(inactivityCountdown.toString());
if (inactivityCountdown < 1) {
clearInterval(intervalid);
Logout();
alert('Your session has been expired and system redirects to login page now.!');
}
}, 1 * 1000);
$(document).delegate(":input", "click change keydown", function() {
inactivityCountdown = initCountdownValue;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="mainpage" style="">
<input type="text"></input>
<input type="button" text="test"></input>
<div>
Counter:
<div id="counter"></div>
</div>
</div>
<div id="loggedout" style="display:none">
You are logged out. To login, click <a id="login" href="#">here</a>
</div>
Of course, in a production environment you would remove the alert and just redirect the user to a logout page. This is just for demo purpose.