Talha Bin Shakir
Talha Bin Shakir

Reputation: 2561

Java Script function call on body load

I have a java script function that i have called on body load mousemove() the function is working but the problem is that function is not overloading. Here is the code:

 function timeout(){  
        setTimeout ("logout()",60000);

        }
     function logout()
        {    
         parent.parent.location="logout.php";
         } 

<body onmousemove="timeout()" >

now the problem is it calls on body load and whenever mouse moves but the page still move to the logout page after the specified time however it should override the time whenever mouse moves and the function calls.

Upvotes: 0

Views: 958

Answers (1)

Matthew Crumley
Matthew Crumley

Reputation: 102775

Each time you call setTimeout it adds another call to the queue. In other words, you aren't replacing the current timeout. To fix it, you will need to cancel the existing timeout event before you start another one by calling clearTimeout with the value of the previous call to setTimeout.

var timeoutID = null;
function timeout() {
    if (timeoutID !== null) {
        clearTimeout(timeoutID);
    }
    timeoutID = setTimeout(logout, 60000);
}

I also changed the call to setTimeout to pass a reference to the logout function instead of a string. It's best to avoid passing a string since it uses eval and isn't necessary.

Upvotes: 3

Related Questions