cshu
cshu

Reputation: 5944

Is race condition possible in Javascript? (e.g.: I want to get and set value atomically)

I did a lot of searching but still cannot figure it out.

It's simple, a global variable has initial value of false;

var globalVar = false;

setTimeout is used twice to call the same function:

function(){
    if(!globalVar){
        globalVar = true;
        alert('show only once');
    }
}

So is alert called only once? Or race condition is possible?

Upvotes: 1

Views: 145

Answers (2)

Los Frijoles
Los Frijoles

Reputation: 4821

Not in your case. Javascript is run in a single threaded environment. One of your timeouts will execute completly before the other is able to execute, meaning that when the other executes, it will see that globalVar is true.

The only concurrency issues that can happen is if you wait for IO, a timeout, or something like that. At that point, other javascript is allowed to execute. No code will ever interrupt other code in order to execute.

For example:

setTimeout(function () { alert('hi!'); }, 1000);
while(true) {}

You will never see the alert since the while loop will busy wait, chomping up the javascript thread for the other code and never giving the timeout an opportunity to execute.

Upvotes: 4

Kyle
Kyle

Reputation: 33701

JavaScript is single threaded, so I don't believe this is possible.

Upvotes: 0

Related Questions