通过parms进入javascript循环的时间

时间:2014-12-11 21:05:16

标签: javascript html5 function settimeout timing

任何人都可以给我一个如何计时这个功能的建议: 我正在尝试执行:

GameBaccarat.prototype.playHands = function(requests) {
    for (var i = 0; i < 3; i++) {
        if (game.instance.players[i]) {
            var hand = i;
            game.instance.hand = i;
            this.activeHands += 1;
            var request = requests[i];
            connector.sendRequest(request, function() {
                var xhr = this;
                game.instance.handleDealResult(hand, xhr)
            });
        }
    }
}

喜欢:

setTimeout(function(){connector.sendRequest(request, function() {var xhr = this; game.instance.handleDealResult(hand, xhr) });}, i*200);

但到目前为止还没有成功..请帮助:)

P.S。 我尝试传递,var that = this,并将其添加到超时,剂量工作:(

尝试:

                var that = this;
                setTimeout(function(){
                connector.sendRequest(request, function() {
                var xhr = that; 
                game.instance.handleDealResult(hand, xhr) });
                }, i*200, that);

没有工作,只是崩溃了回调:(

1 个答案:

答案 0 :(得分:0)

如果你只是想对多个请求进行排序,你可以这样做,只有当前一个请求完成时才启动下一个请求,并且你保留了一个计数器来确定你做了多少:

GameBaccarat.prototype.playHands = function(requests) {
    var requestCntr = 0, numRequests = 3;
    var xhr = this;
    function next() {
        if (requestCntr < numRequests && game.instance.players[requestCntr]) {
            game.instance.hand = requestCntr;
            xhr.activeHands += 1;
            connector.sendRequest(requests[requestCntr], function() {
                game.instance.handleDealResult(requestCntr, xhr);
                ++requestCntr;
                next();
            }
        }
    }
    next();
}

如果您想在请求之间进行排序和添加延迟,则可以添加setTimeout()延迟来启动下一个请求:

GameBaccarat.prototype.playHands = function(requests) {
    var requestCntr = 0, numRequests = 3;
    var xhr = this;
    function next() {
        if (requestCntr < numRequests && game.instance.players[requestCntr]) {
            game.instance.hand = requestCntr;
            xhr.activeHands += 1;
            connector.sendRequest(requests[requestCntr], function() {
                game.instance.handleDealResult(requestCntr, xhr);
                ++requestCntr;
                // 1 second delay before next requeset
                setTimeout(next, 1000);    
            }
        }
    }
    next();
}