Is javascript "truly parallel"?

时间:2018-01-23 19:19:50

标签: javascript node.js asynchronous parallel-processing settimeout

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 个答案:

答案 0 :(得分:3)

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.