1

Can 2 asynchronous functions execute at the same time? For example in the code below, is it possible that the command let xEquals2 = x === 2; from the first setTimeout gets executed, then the same command from the second setTimeout, and finally the if block from the first setTimeout. Or to make the question simpler will the code below always print out the number 2 two times, or is it possible that it will print out 2 and 3 or 3 and 3?

let x = 1;

setTimeout(() => {
    let xEquals2 = x === 2;
    if (!xEquals2) {
        x++;
    }
    console.log(x);
}, 1000);

setTimeout(() => {
    let xEquals2 = x === 2;
    if (!xEquals2) {
        x++;
    }
    console.log(x);
}, 1000);
1

1 Answer 1

4

JavaScript uses a event loop which is not like threads that other platforms have. Hence the first callback will execute first, then the second, so your result will be 2, 2.

Sign up to request clarification or add additional context in comments.

5 Comments

Does that mean once one async function starts executing, it won't get interrupted by any other async function until it's done?
@TheOneWhoMade that's not true for javascript.
@DanielA.White I guess you meant result will be 2, 2? I tried suggesting edit, but it has to be at least 6 characters :)
@marko yea, i just had hard time finding your logic.
Note that JavaScript is single threaded. It is important not to confuse concurrency and asynchrony. Interleaved IO provides IO parallelism because the CPU is not waiting for each IO operation to complete. For CPU bound work, JavaScript will limit you to 1 core.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.