【问题标题】:setTimeout pass parameter in for loop [duplicate]for循环中的setTimeout传递参数[重复]
【发布时间】:2018-04-26 09:43:03
【问题描述】:

我创建了一个数组。我想用 settimeout 发送 ajax 请求。但我无法在 settimeout 中获取参数。当我打印控制台日志变量时,我未定义。我该如何解决这个问题?

控制台日志结果

i undefined

Javascript 代码

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

【问题讨论】:

    标签: javascript angularjs closures settimeout


    【解决方案1】:

    您不需要.bind()。使用letconst 而不是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);
    }

    或者只是将i 作为附加参数传递给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);
    }

    【讨论】:

      【解决方案2】:

      添加 i 作为 setTimeout 的第三个参数来封装它:

      setTimeout(function(i){ // <--  ... and retrieved here again
         console.log(i);
      }, i * 2000, i);// <--- i is stored here ...
      

      【讨论】:

        猜你喜欢
        • 2011-09-27
        • 1970-01-01
        • 2016-08-30
        • 2010-12-19
        • 2014-05-18
        • 2011-06-13
        • 2019-10-21
        • 1970-01-01
        相关资源
        最近更新 更多