What is the difference in the use of the below methods?
First Method :
for(var i = 0; i < 10; i++) {
(function(e){
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
for(var i = 0; i < 10; i++) {
createTimeoutFunction(i);
}
Second Method :
function createTimeoutFunction(e){
setTimeout(function() {
console.log(e);
}, 1000);
}
for(var i = 0; i < 10; i++) {
createTimeoutFunction(i);
}
I am new to node js and in using closures. Though both methods return the same output but the second method runs with error. I am not understanding why do we need to use two loops as in the first method. Can't we just execute as like the second method?