i have done a simple page to move to another page when session expires. I have set the time as 50 seconds and after that it will move to a page But unfortunately its not moving and i am helpless to know where is the wrong. I would be very much grateful if you please solve my problem
function x(){
var timeOut =<%=session.getAttribute("login")%>;
var checkTimeout;
checkTimeOut = function(){
if(timeOut==null || timeOut==""){
window.location.replace("failedSession.jsp");
//document.getElementById("b").innerHTML="session timed out";
// redirect to timeout page
}else{
window.setTimeout(checkTimeOut, 1000); // check once per second
}}
checkTimeOut(); // this is where you insert checkTimeOut function so that when you call x(), this will execute in the end.
}
The code you have pasted does not seem to be invoking the checktimeout function initially. This applies to your revised code as well. It is only defining the function checktimeout().
I would add an onload function call to the body tag which invokes the checktime out the first time.
function startTimeoutCheck() {
window.setTimeout(checkTimeout, 1000);
}
<body onload="startTimeoutCheck()">
....
</body>
The checktimout variable should obviously be in the scope (global) of the above function.
The problem with your code:
Nowhere in your code, you are calling checkTimeOut();
. Which is why it is not being executed. You should have checked the execution of the function by putting alert
inside the function. Probably do it during body onload
as @rgeorge
has suggested.
Note: Your logic looks alright. Also have habit of putting semicolons after javascript
statements as @Mark
has suggested.
Answer Updated:
1) Don't use function name
and variable
name same. For ex: x
. Have names unique. It is conflicting.
2) Your x
is always greater than lastActivity + timeOut
because x
is not increasing (7 > 1+1). Which means else
condition will never execute. Which means checkTimeOut
will never be called.
3) Your function checkTimeOut()
itself will never execute because it is never called from anywhere. You are only executing x()
. This is not sufficient to call checkTimeOut()
.
Answer Updated:
Do as this:
<script type="text/javascript">
function x(){
var timeOut =1;
var lastActivity = 1;
var x=7;
var checkTimeout;
checkTimeOut = function(){
if(x > lastActivity + timeOut){
document.getElementById("b").innerHTML=x;
// redirect to timeout page
}else{
window.setTimeout(checkTimeOut, 1000); // check once per second
}}
checkTimeOut(); // this is where you insert checkTimeOut function so that when you call x(), this will execute in the end.
}
</script>
Your code works fine for me. The DIV
value changes to 7
. And that is what your code does >> http://jsfiddle.net/hmHP9/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.