JS Closure and Scope Preliminary Exploration

    An interesting question I saw before:

    for (var i = 0; i < 5; i++) {
        setTimeout(function () {
            console.log(i);
        },500);
    }

    Loop 5 setTimeouts, you will find that the value of console.log is 5. Why, because setTimeout is an asynchronous function, for will skip directly when it is executed. Obviously, the loop is executed first, and setTimeout starts to execute. At this time, the value of the variable i is already 5, so five 5s are output in succession.

    But we don't need such a result, we want the value of each i in each setTimeout to follow the for loop, so:

    for (var i = 0; i < 5; i++) {
        (function (i) {
            setTimeout(function () {
                console.log(i);
            }, 500);
        })(i);
    }

    We use a closed anonymous function, and pass the variable i into this "closed" function every time we loop, so that each value of i used in setTimeout is different. In my understanding, The closure makes i independent, and 5 different Is are passed in in sequence from the outside. These 5 is are isolated from each other and used in their own setTimeout.

    Regarding what a closure is, there are many answers on the Internet.

    

    


    Back to the topic, the closure is used in order that the value output in each setTimeout is the value in the current loop, but there is also a concise way of writing:

    

    for (let i = 0; i < 5; i++) {
        setTimeout(function () {
            console.log(i);
        }, 500);
    }

    After using let, the scope of i becomes a block-level scope. Each i in setTimeout is the i in the current loop, so the final result is not the same, but the result we want!

 

    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325257447&siteId=291194637