Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

'Closures Inside Loops' , the milliseconds set not work #85

Open
lynxerzhang opened this issue May 7, 2019 · 0 comments
Open

'Closures Inside Loops' , the milliseconds set not work #85

lynxerzhang opened this issue May 7, 2019 · 0 comments

Comments

@lynxerzhang
Copy link

in page interview/js2.html (Closures Inside Loops part), the Solution code is

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

but in this solution, the setTimeout's milliseconds set not work, because you use the IIFE (Immediately Invoked Function Expression), and should become

for(var i = 0; i < 10; i++) {
    setTimeout((function(i) {
      return function() { console.log(i) };  //return a new function
    })(i), 10)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant