当状态完成Javascript时中止间隔

时间:2014-10-17 13:03:00

标签: javascript jquery ajax setinterval

当我从请求中获得的所有状态都处于称为“成功”的状态时,我试图中止我的Interval。 Interval被正确停止了,但似乎它们很快停止了,我不是Javascript专家所以我的代码必须有问题,有人看看$ get请求和calcul之间是否存在同步问题"成功"

var tid = setInterval(update_status, 2000);

function update_status(){

    var task_table = $("#task_table");
    var task_table_rows = $(task_table).find('tr');
    var task_table_length = task_table_rows.length;
    var id_table = [];
    var state_counter = 0;

    //Get id's of the visible table and stock them in id_table

    for(var i = 0; i<task_table_rows.length;i++){

        id_table.push(task_table_rows[i].id);

    }

    //Make the request and update the task state_counter

    for(var i = 1; i<id_table.length; i++){

        state_counter = change_state(i, task_table_rows[i], state_counter);

    }

    //Calcul the max number of task which can became in the state "success"

    var max_number_success = id_table.length - 1;

    //If the number of "success" is the number of tasks then stop the Interval

    if (state_counter == max_number_success){

        abortTimer();

    }



    function change_state(i, task_table_row, state_counter){

        $.get( "/task/id="+id_table[i]).done(function(data){

            task_status = data["task"]["status"];

            //Change HTML class here and others stuff...

        });

        if(task_status == 2){
            return (state_counter + 1);
        }else{
            return state_counter;
        }


    }

    function abortTimer(){
        clearInterval(tid);
    }

}

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要改变您对问题的看法。由于您正在进行AJAX调用,因此您无法从中返回。相反,您必须提供一个回调机制,以便在响应准备就绪时执行。看看代码的这个修改(更改部分)版本:

// Calculate the max number of task which can became in the state "success"
var max_number_success = id_table.length - 1;

// Make the request and update the task state_counter
for (var i = 1; i < id_table.length; i++) {
    change_state(i, task_table_rows[i], state_counter, function (count) {

        state_counter += count;

        // If the number of "success" is the number of tasks then stop the Interval
        if (state_counter == max_number_success) {
            abortTimer();
        }
    });
}

function change_state(i, task_table_row, state_counter, callback) {
    $.get("/task/id=" + id_table[i]).done(function (data) {
        task_status = data["task"]["status"];
        callback(task_status == 2 ? 1 : 0);
    });
}

注意如何在callback函数中使用新的change_state参数,以及如何在循环中为change_state调用提供一个无穷大的函数。