Question d’entretien chez 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.

Réponses aux questions d'entretien

Utilisateur anonyme

22 avr. 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

Utilisateur anonyme

3 juil. 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