views:

78

answers:

3

I have some code that I'd like to run on a page. My problem is that I don't want it to be run more than once at any one point. It can run multiple times, but just not while another instance of itself is running. I'm using jQuery and loading ajax content.

I just need something that prevents users from clicking hundereds of times and building up the que and pinging my server heaps.

Is this possible?

Thanks.

+1  A: 

Just keep a variable to flag whether it's running or not:

var running = true;

... complete: function() { running = false; }
Greg
+3  A: 

If it's just the one function being called in different areas, sounds like you're just wanting some sort of basic semaphore test, e.g:

isRunning = false;

function whatever() {

   if (!isRunning) {
      isRunning = true;
      $.ajax(...., function() {
          isRunning = false;
      });
   }
}

This question looks slightly related.

RE your edit: It's also worth noting that whatever javascript solution you put in place here to avoid a barrage of requests should additionally be considered on the server side.

Gavin Gilmour
You nailed perfectly, thanks man.
I'm aware of the implications of a DoS attack.
A: 

I think it would be more user-friendly if you disabled your controls for the time the ajax request is on its way.

This way not only would you be saved from mass clicking, but also the user would know that there is no point in killing the mouse.

Zed