티스토리 뷰

JavaScript

Single-thread in JavaScript

seoca 2019. 9. 6. 06:44

 

Java Script is a single thread, not multi-thread. If there is another function in use, other functions should wait in Queue until it's done. Java and C# allow multi-thread.

 

자바스크립트는 single-thread 이므로 앞선 실행문이 call stack 에서 실행되는 동안 Queue(Java Script event 엔진이 주기적으로 할 일 확인하는 곳)에서 앞선 실행문이 끝나기를 기다린다.

 

 

 

Example Code

 
function first(){
    setTimeout(function (){
        console.log('start timer')
    }, 1500); // It's supposed to start after 1.5sec after the function starts
 
    //This for loop takes 3 seconds.  
    for(let i=1; i<4;i++){
        perSecond(); //it works every 1second.
        console.log(i)
    }
    console.log('for loop is done');
}
 
first(); //When this function starts, setTimeout works after the for loop get done.
         //It doesn't matter the setTimeout is supposed to work in 1.5sec. 
         //Because JavaScript is a single thread. 
 
console.log('main function');
 
 

 

 

 

Reference

https://www.youtube.com/watch?v=iNH4UQxZexs

'JavaScript' 카테고리의 다른 글

Rest parameter  (0) 2020.08.26
How to run your Javascript test code in Chrome  (0) 2020.07.28
Promise  (0) 2019.09.04
Callback function in JavaScript  (0) 2019.08.28
Arrow function in JavaScript  (0) 2019.08.28