Why not try a different approach instead of using a single 15-minute timer? How about setting the interval to 1 minute and implementing a countdown counter in your event handler?
This counter can be easily reset by various events like AJAX calls, click events, etc., which can be triggered effortlessly using jQuery's .delegate
or .on
methods.
If there are no resets happening, once the countdown reaches 0, you can proceed with the redirect process.
var inactivityCountdown = 15;
intervalid = window.setInterval(function Redirect()
{
inactivityCountdown--;
if (inactivityCountdown<1) {
clearInterval(intervalid);
alert('Your session has expired, system will now redirect to the login page!\n\n');
window.location.href='../index.aspx';
}
}, 60*1000);
This method allows for easy resetting of the inactivityCountdown
counter before it expires. Just remember to clear the interval when performing the redirect.
In the example below, I have used a 10-second countdown for testing purposes instead of minutes. You can enter text into the field or click the button to reset the countdown:
You will receive a logout message followed by a prompt to log back in via a link (simulating 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 = "";
// Alternatively use: 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 expired, system will now redirect to the login page!');
}
}, 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>
In a real production environment, it is recommended to remove the alert message and simply redirect the user to a designated logout page. The alert is purely for demonstration purposes.