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

386
Visualizações
Is the function order guaranteed?
let x = 0;
function a() {
    console.log("called a()");
    for (let i=0; i<123456789; ++i) {
        x += Math.sqrt(2);
    }
    console.log("x = "+x);
}
function b() {
    x = undefined;
    console.log("called b()");
}
setTimeout(b, 20);
a();

output:

called a()
x = 174594265.7306214
called b()

b should have been called sooner, but it waited until the function a completed.

I know js uses only one thread, but the processor could have switched between executing a and b during a's execution. Does the processor always execute only one function at a time (if there is no await inside)? In nodejs and in website javascript?

EDIT:
Here is an await example:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
let x = 0;
async function a() {
    console.log("called a()");
    await sleep(1000);
    for (let i=0; i<123456789; ++i) {
        x += Math.sqrt(2);
    }
    console.log("x = "+x);
}
function b() {
    x = undefined;
    console.log("called b()");
}
setTimeout(b, 20);
a();

output:

called a()
called b()
x = NaN

notice how x becomes NaN, since b is executed during a

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

b should have been called sooner, but it waited until the function a completed.

No. b should be called after your synchronous code has executed because that's when a function passed to setTimeout is called.

Callback function of setTimeout is scheduled to run after the delay you specify as a second argument to setTimeout. This delay is the minimum amount of time it will take to run the callback function scheduled using setTimeout.

Once the timer expires, that callback function is put in a task queue and from there it is pushed to the call stack BUT it is only pushed once the call stack is empty.

In your case, call stack will be empty when your script has finished its execution.

I know js uses only one thread, but the processor could have switched between executing a and b during a's execution

That's not possible with only 1 thread. In Javascript, only one thing executes at a given time, unless you use another thread.

Does the processor always execute only one function at a time (if there is no await inside)

Yes. Even with await, function is paused until the promise is settled. Once the promise settles, that function continues execution and at that time, nothing else executes.

Edit

notice how x becomes NaN, since b is executed during a

No, there is no interference here. Function a is executed synchronously until the following statement

await sleep(1000);

While the function a is paused, waiting for the promise returned by sleep(...) to settle, during this time, function b is executed because its timer has expired and the call stack is empty.

Since both functions assign to same variable x, value of x is NaN because its value before function a resumes is undefined and performing addition on undefined leads to NaN.

over 4 years ago · Santiago Trujillo 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