I am trying to understand how javascript handle concurrency with this script:
let buffer = [], total = [], count = 0;
const a = setInterval(() => {
buffer.push(count);
count++;
}, 1);
const b = setInterval(async () => {
await new Promise(resolve => setTimeout(resolve, 500));
total = [...total, ...buffer];
buffer = [];
}, 1);
setTimeout(() => {
clearInterval(a);
clearInterval(b);
console.log(total.length + " elements");
for (let i = 0; i < total.length; i++) {
if (i !== total[i]) {
console.log("Error on " + i);
}
}
}, 10000);
Example of output:
8227 tries
Done !
From what I understand, intervals A and B will run in a single thread, and while interval B is waiting for the promise to resolve, interval A will keep running.
However interval A will never be able to run after the promise is resolved and B's execution is resumed, so I shall never see an Error on x, is that correct ?
I tried to replace the interval like below and get errors, so I think I am correct, but I'd like to be 100% sure about this.
const b = setInterval(async () => {
total = [...total, ...buffer];
await new Promise(resolve => setTimeout(resolve, 500));
buffer = [];
}, 1);