Skip to content

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

@lynxerzhang

Description

@lynxerzhang

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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions