James Daley
James Daley

Reputation: 289

jquery: stop a function executing if a user clicks a div?

I have the following jquery code which redirects the user after 3 seconds. How can I prevent this from happening / stop the function from executing when a user clicks on my div 'stay_loggedin'?

here is what I've tried but it doesn't work and stops the code from running at all:

<script>
    $('#stay_loggedin').click(function(){  
    window.setTimeout(function() {
    window.location.href = 'include/timeout.php';
}, 3000);
    cancel = true;
});
</script>

Upvotes: 0

Views: 136

Answers (1)

Max Zuber
Max Zuber

Reputation: 1229

There is a special method clearTimeout() to cancel the timer. It prevents useless condition checks, and works by design.

var logoutTimer = window.setTimeout(function() {
  window.location.href = 'include/timeout.php';
}, 3000);

$('#stay_loggedin').click(function() {
   window.clearTimeout(logoutTimer);
});

Upvotes: 1

Related Questions