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

153
Vistas
JavaScript Function returns twice but is only called once

I tried to figure out the problem but this code logs twice. It logs John before the delay and "Robert" after the delay.

let myName = 'John';
delayer();
myName = 'Robert';
function delayer() {
    console.log(myName);
    setTimeout(() => console.log(myName), 1500)
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

() => console.log(myName) is the same as function() { return console.log(myName); }.[1]

The resulting function reference is passed to setTimeout which arranges to call it after the specified delay. setTimeout doesn't wait for the delay to occur before returning. It returns immediately. So myName has been changed by the time the anonymous function has been called.


  1. There are differences between the two approaches as itemized in the first link, but they don't come into play here.
about 4 years ago · Juan Pablo Isaza 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