Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!