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

151
Visualizações
Why setTimeout(code...,1) is executed first than setTimeout(code... ,0)?

I tested this code and the result I expected was getting the Chicken log first, but I was wrong, everytime I run this code I get the Egg log first, does anybody knows whats going on here?

setTimeout(() => {
  console.log("Egg");
}, 1);

setTimeout(() => {
  console.log("Chicken");
}, 0);

Edit: Notice that this behaves differently if those delays are 101ms and 100ms respectively, so the behavior changes even if the difference on the timer is still 1ms

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The time is in milliseconds that the timer should wait before the specified function or code is executed. 1000ms will be 1 sec and since your input to a parameter was 1ms JS just displayed it in the order it was written because 1ms and 0ms were comparable. Moreover, you can use async-await to wait for tasks that would take longer. For instance,

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function printOnTime() {{
    console.log("Chicken")
    await timeout(1000); 
    console.log("Egg")
}}


printOnTime();

In this example, Chicken will be printed asap however in order to print Egg it will wait for 1 sec (1000ms) and finally print Egg.

about 4 years ago · Juan Pablo Isaza Relatório
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