Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
javascript single-threaded , how asynchronous is implemented

It is acknowledged that JavaScript is single-threaded ,but while i try the code below, when i use setTimeout and Promise, it's obviously that they runs asynchronously

function testTimer(){
  setTimeout(()=>{console.log(2)},100)
}
function testLoop(){
    for(let i = 0; i < 1e3; i++){}
    console.log(3)
}
function testPromise(){
     return new Promise((resolve)=>{
        for(let i = 0; i < 1e3; i++){}
        resolve();
    })
}
console.log(1)
testTimer();
testLoop();
console.log(4)
testPromise().then(()=>{console.log(5)})
console.log(6)

If javascript is completely single-threaded, the console should print 1, 2, 3, 4, 5, 6 in order. But the single threaded feature can only be seen in testLoop(), we can see that the use of Promise and setTimeout allow the code below run ahead, could someone please tell how's this achieved?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda