Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

385
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda