I am trying to understand callbacks via setTimeout
function.
I have two sets of code :
for (var i = 1; i <= 10; i++) {
(function(callback,i){
setTimeout(function(){
callback(i)
}, 0);
})(function(val){console.log(val)},i);
It works fine printing 1,2,3,.... 10
But when i am trying to abstract setTimeout
's callback function as :
for (var i = 1; i <= 10; i++) {
(function(callback,i){
setTimeout(func, 0);
})(function(val){console.log(val)},i);
}
function func(){
callback(i)
}
It gives me error stating
Uncaught ReferenceError: callback is not defined
I know there is some issue with lexical scoping of declaration of that func function. But not able to comprehend the reason. Please do help me understand this.