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.
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