Frage im Vorstellungsgespräch bei LinkedIn

Analyze a horrible JavaScript function to determine the problems. Essentially a nasty for loop with a setTimeout inside that did a console.log of the loop iterator's value.

Antworten zu Vorstellungsgespräch

Anonym

22. Apr. 2015

Just add a Closure to it. for (var j=0; j< 10; j++) { (function(j) { return setTimeout[function() { console.log(j); }, 100) })(j); }

2

Anonym

3. Juli 2014

Trick question of course, the setTimeout makes it so that the iterator has gone to the full value of N by the time the setTimeout fires, so all statements print the same value. The fix? Use closures/self executing function to capture the value when the setTimeout is first set so that it maintains the correct corresponding value.

6