当我从请求中获得的所有状态都处于称为“成功”的状态时,我试图中止我的间隔。 Interval 已正确停止,但似乎停止得太快了,我不是 Javascript 专家,所以我的代码一定有问题,有人看看 $get 请求和“成功”的计算之间是否存在同步问题“?
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);
}
}
谢谢。
最佳答案
你需要改变思考问题的方式。由于您正在进行 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);
});
}
请注意如何在 change_state
函数中使用新的 callback
参数,以及如何为循环中的 change_state
调用提供匿名函数。
关于javascript - 状态完成时的中止间隔 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425650/