1

I have this bit of code on a loading screen which waits five seconds before logging the user in:

  setTimeout(
    function() {
        $.doPost("http://mysite.com", {
                username: results.rows.item(0).username,
                password: results.rows.item(0).password
            });
  }, 5000);

While the page is waiting, I also have a button on the screen that says 'Log out' and if clicked, need this post to not happen. Basically, the user has five seconds to hit logout before automatically being logged in. The Log out button has an onClick and no matter what I put in that function, it continues with the login, how can I have that button stop the $.doPost from happening?

Jasper
  • 75,717
  • 14
  • 151
  • 146
user989557
  • 929
  • 2
  • 11
  • 18
  • possible duplicate of [stop function that run with setTimeout](http://stackoverflow.com/questions/5786646/stop-function-that-run-with-settimeout) – Richard JP Le Guen Nov 28 '11 at 19:25

4 Answers4

6

First, assign your timeout to a variable:

var timer = setTimeout(

function () {
    $.doPost("http://mysite.com", {
        username: results.rows.item(0).username,
        password: results.rows.item(0).password
    });
}, 5000);

Then, in your logout button code use clearTimeout():

$('#button').click(function () {
    clearTimeout(timer);
}

Be careful about your variable's scope, however, seeing as it's used in two separate functions. It might be a good idea in this case to declare it in the global namespace:

var timer;

$('#login').click(function () {
    timer = setTimeout(

    function () {
        $.doPost("http://mysite.com", {
            username: results.rows.item(0).username,
            password: results.rows.item(0).password
        });
    }, 5000);
});

$('#logout').click(function () {
    clearTimeout(timer);
});

If you've put both events in $(document).ready(), you can declare var timer in there instead to stop any pollution.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
1

Save the return value of setTimeout() as a "timerHandle", and if you want to cancel that timeout, call "clearTimeout()" on that timerHandle.

rob
  • 9,933
  • 7
  • 42
  • 73
1

You need to save the result from setTimeout and call clearTimeout on that result to cancel it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Can you use a global boolean to check if the logout button has been clicked? Something like this:

setTimeout(
    function() {
        if(!logoutClicked) {
            $.doPost("http://mysite.com", {
                username: results.rows.item(0).username,
                password: results.rows.item(0).password
            });
        }
     }
, 5000);
bfink
  • 158
  • 2
  • 10
  • Saving the timer to a variable is the obvious answer - I didn't even think to do that XD – bfink Nov 28 '11 at 19:31