setTimeout inside for loop

what actually happen after creating different sope using IIFE as variable j inside the function will have value of i copied to it which must have been also increased to end value of i in the loop.

code:
for (var i = 0; i < 10; i++) {
(function(j) {
setTimeout(function() {
console.log(j);
}, 100);
})(i);
}

Hi @akashagarwal1321,
If a more than one timeout requests are made, the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid successive order.
Each of the timer handler functions will share the same variable “i”. By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private “i” to use.You have to arrange for a distinct copy of “i” to be present for each of the timeout functions.If you want the handlers to be called at intervals, Use setInterval() , which is called exactly like setTimeout() but it will execute more than once after repeated intervals

To read more about setTimeout function inside loops you can refer the provided link.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.