title: Long polling with Ajax with sleep()/time_sleep_until() in while() loop
body: <p>I'm willing to set up a long polling Ajax call to check for orders in my e-commerce web app. There is a specificity in this application in the way that customers are able to place order in the future. As such, in the admin panel, we have past orders and futures orders (that can be 2 months or 20 minutes in the future).</p>
  
  <p>Basically, I want the admin user in the back-end to be warned as soon as a future order comes to an end (the future date reaches the current time). To proceed, I make the user admin doing an Ajax call (as soon as they are connected to the admin) to the server to check for futures orders to arrive. This Ajax call is a long polling request as the call waits for the server to deliver result. If server has nothing to offer, the request keeps pending until there is an order to show.</p>
  
  <p><strong>Ajax request</strong></p>
  
  <pre><code>    (function poll() {
          setTimeout(function() {
              $.ajax({
                  url: '{{ path('commande_check') }}',
                  method: 'post',
                  success: function(r) {
                      if(r.ids) alert('New order!'); // I've simplified this part of the code to make it clean, admin are actually warned through Node.JS server
                  },
                  error: function() {},
                  complete: poll
              });
          }, 5000);
      })();
  </code></pre>
  
  <p><strong>{{ path('commande_check') }}</strong> (edited from <strong>Edit2</strong>)</p>
  
  <pre><code>public function checkAction(Request $request)
  {
  
      if($request-&gt;isXmlHttpRequest())
      {
          $response = new Response();
          $em = $this-&gt;getDoctrine()-&gt;getManager();
  
          $ids = array();
          while(!$ids)
          {
              $ids = $em-&gt;getRepository('PaymentBundle:Commande')-&gt;findNewestOrders(new \DateTime());
              if($ids)
                  break;
              else
                  time_sleep_until(time() + self::SECONDS_TO_SLEEP);
          }
  
          if($ids)
          {
              return new JsonResponse(array(
                  'ids' =&gt; $ids
              ));
          }
          $response-&gt;setStatusCode(404);
          return $response;
      }
  
      $response = new Response();
      $response-&gt;setStatusCode(405);
      return $response;
  }
  </code></pre>
  
  <p><strong>findNewestOrder() method</strong></p>
  
  <pre><code>public function findNewestOrders(\DateTime $datetime)
  {
      $query = $this-&gt;createQueryBuilder('c')
                    -&gt;select('c.id')
                    -&gt;leftJoin('Kt\PaymentBundle\Entity\Paiement', 'p', \Doctrine\ORM\Query\Expr\Join::WITH, 'p.id = c.paiement')
                    -&gt;andWhere('p.etat = 0')
                    -&gt;where("DATE_FORMAT(c.date, '%Y-%m-%d %H:%i') = :date")
                    -&gt;setParameter('date', $datetime-&gt;format('Y-m-d H:i'))
                    -&gt;andWhere('c.kbis IS NULL')
                    -&gt;andWhere('c.notif = 0')
                    -&gt;getQuery();
  
      return $query-&gt;getArrayResult();
  }
  </code></pre>
  
  <p>My problem is the alert sometimes never get shown whereas the record in the DB gets updated. The weirdest things is it sometimes happens even when I've leaved the page making the Ajax call like if it keeps running in the background. I think the problem comes from the <code>time_sleep_until()</code> function. I tried with <code>sleep(self::SECOND_TO_SLEEP)</code> but the problem was the same.</p>
  
  <p>Any help would by gladly appreciated. Thanks!</p>
  
  <p><strong>Edit 1</strong></p>
  
  <p>I sense there is something to do with <code>connection_status()</code> function as the while loop appears to continue even if the user has switched page causing the field <code>notif</code> to be updated in the background.</p>
  
  <p><strong>Edit 2</strong></p>
  
  <p><a href="https://stackoverflow.com/a/29206054/2788131">As per my answer</a>, I've managed to overcome this situation but the problem still remains. The admin does get the notification properly. However, I do know the Ajax call still keeps going on as the request has been made.</p>
  
  <p>My problem is now: <strong>could this result in a server resources overload?</strong>
  I'm willing to start a bounty on this one as I'm eager to know the best solution to achieve what I want.</p>