for (var i = 0; i <= 5; i++) { (function (i) { directionsService.route(request, function (response, status) { alert(i); }); }(i)); }