Javascript thread-handling and race-conditions

后端 未结 2 852
梦毁少年i
梦毁少年i 2021-01-13 08:51

Lets asume I have a code like the following:

var shared = 100;
function workWithIt(){
    shared += 100;
}

setTimeout(workWithIt, 500);
setTimeout(workWithI         


        
2条回答
  •  一个人的身影
    2021-01-13 09:15

    AFAIK, there is no multithreading in JS. I changed your example a bit to try to understand what you mean.

    var shared = 100;
    function workWithIt(a){
        shared += a||100;
        console.log(shared);
    }
    
    setTimeout(function(){workWithIt(5);}, 500);
    setTimeout(function(){workWithIt(10);}, 500);
    console.log(shared);
    

    With this code, the result is always (in my testing):

    100
    105
    110
    

    This indicates to me that there is no chaotic or random or even interesting process here. There are certain possibilities to create racing conditions with JS in the browser, but your timing example is not that. Racing requires only a breakdown in predictability of execution order. Maybe if you change your delay from 500 to Math.floor(500 * Math.random()) you would have a racing condition.

提交回复
热议问题