Jonathan Wood
Jonathan Wood

Reputation: 67213

Prevent JavaScript Timer Re-entry

My ASP.NET MVC page uses JavaScript/jQuery to poll my database every second.

This is working but I want to make sure that, if there is a delay, my timer handler won't get called again before it has returned.

In there any trick to this other than storing the timer ID in a global variable, clearing the timer in my handler, and restarting it when my handler is done.

NOTE: I realize every second seems frequent but this code is polling my server after submitting a credit card payment. Normally, it will only run for a second or so, and I don't want the user to wait any longer than necessary.

Upvotes: 2

Views: 521

Answers (3)

RestingRobot
RestingRobot

Reputation: 2978

In my personal experience a "global", (inside of the root function), variable works very well in this instance so that you can control when to clear and restart. If the response is really as quick as you say, this shouldn't cause too much overhead, (clearing/resetting), and will allow to account for these type of situations.

Upvotes: 0

Scott Sauyet
Scott Sauyet

Reputation: 50797

Not really, although I wouldn't recommend using a global variable. Stick it inside some function.

But are you really sure you need to poll every second? That's an extremely chatty interface.

Upvotes: 1

Rob W
Rob W

Reputation: 349032

Polling every second? That's quite heavy!

That aside, you won't have this issue when setTimeout is used instead of setInterval. The latter ensures that a piece of code is run x times given a interval, while the former ensures that there's a delay of at least x milliseconds.

function some_poller() {
    $.ajax({
       url: '/some_page',
       success: function() {
           setTimeout(some_poller, 1000);
       },
       error: function() { // Also retry when the request fails
           setTimeout(some_poller, 1000);
       }
    });
}

// Init somewhere
some_poller();

Upvotes: 5

Related Questions