-3

I don't know this question is relevant to Stack Overflow. But I don't know where to ask.

Does race condition applicable for JavaScript since I learnt JavaScript as single thread language.

I have seen few examples of YouTube videos about race condition in JavaScript. But nothing clarifying me. If anyone can explain to me how race condition is possible in single-threaded JavaScript world?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
user6410893
  • 53
  • 3
  • 9

1 Answers1

1

JavaScript is indeed a single thread language BUT supports asynchronous code.

What does that mean?

It means no two blocks of code will ever be running at the same time. In multithreaded languages like Java two functions can be running at the very same time, each on its own thread. In JavaScript though, even with asynchronous code, all the code that needs to run will be placed into one "queue", it is just that the order of code ends up in the "queue" depends on whether your logic is synchronous or not.

An example:

const work = (a) => {
  console.log('Starting work: ' + a);

  // Here we simulate some long operation
  for (let i = 0; i < 100000; i++) {
    document.querySelector('a[href]');
  }

  console.log('Finished work: ' + a);
};

work(1);
work(2);
work(3);
setTimeout(() => work(4), 2);
setTimeout(() => work(5), 1);
work(6);
work(7);

What you will see on the output is:

Starting work: 1
Finished work: 1
Starting work: 2
Finished work: 2
Starting work: 3
Finished work: 3
Starting work: 6
Finished work: 6
Starting work: 7
Finished work: 7
Starting work: 4 <- This one was async
Finished work: 4 <- This one was async
Starting work: 5 <- This one was async
Finished work: 5 <- This one was async

So even though there was some asynchronous code, work function always started and finished without the asynchronous code "interrupting" it halfway through the execution.

Ján Jakub Naništa
  • 1,880
  • 11
  • 12