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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With