Trying to print series of numbers inside for loop using closures and with let:
Consider the following example:
for(var i=1; i<10; i++){
setTimeout(function(){
document.write(i);
}, 1000);
}
Output is:
101010101010101010
With Closures:
for(var i=1; i<10; i++){
(function(x){
setTimeout(function(){
document.write(x);
}, 1000);
})(i);
}
Output is:
123456789
Without closure, just using ES6 let:
for(let i=1; i<10; i++){
setTimeout(function(){
document.write(i);
}, 1000);
}
Output is:
123456789
Trying to understand if we still need closures using IIFE blocks moving towards ES6?
Any good example if we really need closures with ES6?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…