0

This is working fine, but I'm trying to find a good solution to stop Javascript setInterval when all responses has been fetched from a database through Ajax.

A for loop inside a for loop could work, I think?!

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>
}

Let's say we have 3 responses from database, and we have 3 divs with 3 different ids.

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;
     } 
  }
}
John Slegers
  • 45,213
  • 22
  • 199
  • 169
gr3g
  • 2,866
  • 5
  • 28
  • 52

1 Answers1

2

Save interval identifier to the accessible object or variable:

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

then use window.clearInterval() + return to prevent function execution

// somewhere in getResponse() function
if(... stop condition ...){
    window.clearInterval(window.responseLoopInterval); // remove interval loop
    return; // prevent further function execution
}
BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • The problem is more about the if condition to stop the loop. Ex. with 2 responses, response[1] && response[2] has been set to true. then if condition will look like this: if(response[1] && response[2]). But the number of responses is a variable, so I don't know how much response[i] I'll have... – gr3g Aug 31 '14 at 09:45
  • 1
    @user1824508 `if(response.length >= 2){ ...stop loop... }` ? – BlitZ Sep 01 '14 at 02:43