Search code examples
javascriptangularjsclosuressettimeout

setTimeout pass parameter in for loop


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);
}

Solution

  • 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);
    }