1. Introduction

Write down a big factory interview question every day

2. The title

Modify the following code to print 0-9, writing out every solution you can think of

for (var i = 0; i< 10; i++){
    setTimeout(() = > {
	console.log(i);
    }, 0)}Copy the code

3. The parsing

Js is a single thread timer and it’s a macro task and it doesn’t block code execution so by the time the for loop is done I has executed ++ to 10 and it prints 10 times “10”

// Execute the function immediately to hold the closure of the variable value of I
for (var i = 0; i< 10; i++){
    (function(i){
        setTimeout(() = > {
            console.log(i);
        }, 0)
    })(i)
}

// Use the let keyword to declare that a scope is limited to the block level
for (let i = 0; i< 10; i++){
    setTimeout(() = > {
        console.log(i);
    }, 0)}Copy the code

series

  • 1. Interview question 1: “The timer”