<script>The outcome would be "01234" in console.
for(var i=0;i<5;i++){
console.log(i);
}
</script>
And then let put the line "console.log(i);" into a closure.
<script>You would get outcome as "55555" in console after 1 second
for(var i=0;i<5;i++){
setTimeout(function(){
console.log(i);
},1000);
}
</script>
If we want print "01234" which pass the valuable i into closure,
we can use self-executing function/ self-invoking function to capture the value of i :
<script>Outcome "01234" in console after 1 second.
for(var i=0;i<5;i++){
setTimeout(function(){
return function(){
console.log(i);
}();
}(i),1000);
}
<script>
Reference:
https://stackoverflow.com/questions/10855473/passing-parameters-into-a-closure-for-settimeouthttps://www.w3schools.com/js/js_function_closures.asp
No comments :
Post a Comment