Tuesday, July 30, 2019

[javaScript][Resolved] Pass value into closure

Let have a look of an example first :
<script>
for(var i=0;i<5;i++){
    console.log(i);
}
</script>
The outcome would be "01234" in console.

And then let put the line "console.log(i);" into a closure.

<script>
for(var i=0;i<5;i++){
    setTimeout(function(){
        console.log(i);
    },1000);
}
</script>
You would get outcome as "55555" in console after 1 second

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>
for(var i=0;i<5;i++){
    setTimeout(function(){
        return function(){
            console.log(i);
        }();
    }(i),1000);
}
<script>
Outcome "01234" in console after 1 second.

Reference:

https://stackoverflow.com/questions/10855473/passing-parameters-into-a-closure-for-settimeout
https://www.w3schools.com/js/js_function_closures.asp

No comments :

Post a Comment