settimeout – Why doesn't the duration of the function execution increase?

Question:

for (j=1;j<=5;j ++)
{
    (function(i){
        setTimeout(function(){console.log(i)}, j*500)
    })(j)
}

Interested in this particular piece of code, why does the delay not increase by 500 ms? I would be grateful if someone described how the function works.

Answer:

You are essentially running five functions at the same time, i.e. your code is identical:

(function(i){setTimeout(function(){console.log(i)}, 1*500)})(1)
(function(i){setTimeout(function(){console.log(i)}, 2*500)})(2)
(function(i){setTimeout(function(){console.log(i)}, 3*500)})(3)
(function(i){setTimeout(function(){console.log(i)}, 4*500)})(4)
(function(i){setTimeout(function(){console.log(i)}, 5*500)})(5)

Which has the effect of printing five messages to the console at an interval of 500 milliseconds.

Scroll to Top