所有Ajax调用完成后如何停止setInterval?

时间:2014-08-29 08:31:17

标签: javascript php html

这很好用,但是当我通过Ajax从数据库中提取所有响应时,我正在尝试找到一个很好的解决方案来停止Javascript setInterval

for循环中的for循环可以工作,我想?!

HTML:

<!-- code is simplefied, problem is not about syntax, but the way to do it. -->

SELECT id FROM database WHERE x=y

$rows = countrows(); //know how much different output there is

for(i=1; i <= rows; i++) // Show div everytime there's a response
{
$data-> fetch();

<div id="<?php echo "div" . $i;?>"> 
   <?php echo 'id' . $data['id']; ?> 
</div>
}

假设我们有3个来自数据库的回复,我们有3个div个,有3个不同的id s。

使用Javascript:

setInterval(getResponse(), 1000); //execute function every second

getResponse()
{

  for(i=1; i <= $rows; i++)
  {
     //Here is the problem
     //Stop getResponse function execution when all responses has been taken
     if(response[i] && reponse[i] && ...)
     {
       //Stop function
     }

     //Select id . $data['id'] WHERE div . $i = i;
     // GET VARIABLE FROM DATABASE WHERE ID = 'id' . $data['id'];
     if(response)
     {
       //INSERT THIS VARIABLE IN THE RIGHT DIV.
       $response[i] = true;
     } 
  }
}

1 个答案:

答案 0 :(得分:2)

将时间间隔标识符保存到可访问的对象或变量:

window.responseLoopInterval = window.setInterval(getResponse(), 1000);

然后使用window.clearInterval() + return来阻止函数执行

// somewhere in getResponse() function
if(... stop condition ...){
    window.clearInterval(window.responseLoopInterval); // remove interval loop
    return; // prevent further function execution
}