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

181
Vistas
Why does using IIFE in this code, result in vastly different output?

Okay, so in the following bit of code basically I want my function to take an input in milliseconds, and then print out the message with the iteration it's on, and the amount of milliseconds it took. And it just needs to loop.

let count = 0

function timerFunction(miliseconds) {
  setTimeout(function() {
    console.log('This is iteration number: ' + ++count + ' and it took this many miliseconds to do the iteration:' + miliseconds)
    timerFunction(miliseconds)
  }, miliseconds)
}

timerFunction(2000)

That works as intended. All good.

However, if I make that function specified in setTimeout a IIFE function like so:

let count = 0

function timerFunction(miliseconds) {
  setTimeout((function() {
    console.log('This is iteration number: ' + ++count + ' and it took this many miliseconds to do the iteration:' + miliseconds)
    timerFunction(miliseconds)
  })(), miliseconds)
}

timerFunction(2000)

It seems to ignore the timeout, loop really fast, and then node.js gives a stack overflow error.

How come making that function in setTimeout a IIFE function, makes such a difference? I can't get my head around it.

Cheers guys.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In the first example the timerFunction will be called after a minimum of 2000 ms (actually, when the event loop will take that callback function timerFunction from the callback queue after the platform (which can be the browser or node.js) will finish taking care of the count down), so the timerFunction will be called again with it's new stack (recursive).

In your second example, the setTimeout method is invoked immediately (IIFE stand for immediately invoked function expression) because applying the () at the end, hence, the timerFunction is being called again (and again again...), so the 'miliseconds' argument has no actual meaning.

Here is a good article from medium explaining it: https://medium.com/@devinmpierce/recursive-settimeout-8eb953b02b98

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