3

I created an array. I want to send ajax request with settimeout. But I can't get parameter in settimeout. When I print console log variable i is undefined. How can I solve this problem?

Console Log result

i undefined

Javascript Code

$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Hermes
  • 452
  • 10
  • 24

2 Answers2

6

Add i as the third argument of setTimeout to encapsulate it:

setTimeout(function(i){ // <--  ... and retrieved here again
   console.log(i);
}, i * 2000, i);// <--- i is stored here ...
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
5

You don't need .bind(). Either use let or const instead of var...

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (let i = 0; i < $scope.type.length; i++) {
    setTimeout(function () {
        console.log("i", i);

        // your code

    }, i * 2000);
}

or just pass i as an additional argument to setTimeout.

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);

        // your code

    }, i * 2000, i);
}