Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dealing with loops in javascript, only last item gets affected? [duplicate]

Im working with the gm npm module that deals with image manipulation. and i have this code.

for(i=0;i < 4;i++){
    gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) {
         console.log(this.outname + " created  ::  " + arguments[3]); //success
    });
}

this loop is meant to loop through the images array and crop each photo, but it only crops the last one. i think its something to do function invocation and callbacks, but not advanced yet for that level.

like image 802
Unknown Avatar asked Mar 16 '14 14:03

Unknown


1 Answers

Change your code to:

for (var i = 0; i < 4; i++) {
  (function (i) {
    gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) {
         console.log(this.outname + " created  ::  " + arguments[3]); //success
    });
  }).call(this, i);
}

otherwise the value of i will be 3 each time your callback is being invoked.

like image 187
Minko Gechev Avatar answered Oct 20 '22 00:10

Minko Gechev