I often read that you don't have to worry about race conditions in javascript as it's single-threaded. But I believe that it's because of Run-to-completion nature of event loops. Javascrit could still have concurrency issues if it did not had the "Run-to-completion" feature.
Let's consider this code snippet:
1 var pending = [];
2 document.getElementById("submitBtn").addEventListener(function() {
3 var val = document.getElementById("textBox").value;
4 pending.push(val);
5 });
6 setInterval(function() {
7 processValues(pending);
8 pending = [];
9 }, 3000);
Asume that there was no such feature in javascript "Run-to-completion" and any event could be pre-empted to run another event/code.
Now suppose line 7 gets executed and suddenly the event gets pre-empted to process the event at line 3. After executing line 3 & 4, the previous event is resumed from line 8. Now when line 8 gets executed, the newly added value in pending
will be lost because it's neither processed by processValues
function not it's in the pending
array.
A race condition occurred even though it is single-threaded. So, it's not right to say that javascript does not have race conditions because it's single-threaded? Specifically, it's because of Run-to-completion feature of javascript?
EDIT
Apparently, there can be race conditions in javascript. What I was referring to is the certain class of race conditions that does not occur because of single-threaded (or because of Run-to-completion?) nature of javascript. For example, the one I described above.