3

I'm writing some jQuery code that performs a plain ajax call. I've a global Javascript variable that I need to increase thread-safely with every call. If this was Java, I would use synchronized but this is not the case :-)

Here's a code snippet:

var myval;

function myFunc()
{
    $.ajax({
        url: myurl,
        type: 'GET',
        data: { ...my data... },
        success: function()
        {
            myval++;
        }
    });
}

Given that myFunc() is associated with a click event, how can I be sure that myvar is always safely/consistently increased? I know I could maybe use async: false, but I'd prefer to avoid it. I'm not even sure it would work that way.

Thanks for any help!

godzillante
  • 1,174
  • 1
  • 17
  • 32
  • 2
    `everything that happens in an event must be finished before the next event will be processed`, from http://stackoverflow.com/questions/124764/are-mutexes-needed-in-javascript :) – IProblemFactory Aug 01 '14 at 10:18
  • since AJAX is asynchronous by design, I think subsequent calls would read the variable's wrong value. what if I start a call by clicking button A, then *before the first call is finished* I click button B? I can't predict how long each call will take to complete. – godzillante Aug 01 '14 at 10:33
  • thanks @ProblemFactory, I'm reading it – godzillante Aug 01 '14 at 10:33
  • 1
    @godzillante I wouldn't say it's "asynchronous by design" as such, more just "event driven with a single thread". Event happens, code runs, browser twiddles its thumbs until the next event happens, repeat ad infinitum. The code while it's running cannot be interrupted. – Alnitak Aug 01 '14 at 10:57

1 Answers1

4

There's no problem - JS doesn't suffer atomicity problems since there are no (user-visible) threads[*]

Nothing happens in JS except in response to an event or initial script load. It's impossible for a piece of code to misread myval during an increment, because the entire success callback must complete before any other event handling code can start.

[*] Yes, there's WebWorkers, but they use message passing not variable sharing.

Alnitak
  • 334,560
  • 70
  • 407
  • 495