title: Run a loop that ajax loads more elements until an element is found
body: <p>I have an ajax function which loads the next page or results in without refreshing. This works fine, but what I'm aiming to do is run this in a loop until a certain element is loaded in through the ajax call.</p>
  
  <p><strong>jQuery</strong></p>
  
  <pre><code>var ajaxPageNumber = 2;
  function infiniteResults() {
      $.ajax({
          type: 'GET',
          url: '/?page=' + ajaxPageNumber,
          success: function(data) {
              ajaxPageNumber +=1;
              if (data.length) {
                  $('.table tbody').append(data);
              } else {
                  $('&lt;div class="text-center"&gt;&lt;strong&gt;No more results remaining.&lt;/strong&gt;&lt;/div&gt;').insertAfter('.table');
              }
          }
      });
  }
  
  $(document).ready(function() {
          var i = 0;
          while (($('.desired-element').length &lt; 1) &amp;&amp; (i &lt; 50)) {
              infiniteResults();
              i++
              console.log("More results loaded");
          }
      } else {
          console.log("Max tries reached, fail);
      }
  });
  </code></pre>
  
  <p>The problem I'm running into is that it fires all 50 of my loops ajax calls at once, so it appends page 2 of the data 50 times. This happens even though in my test, the desired element is on page 4.</p>
  
  <p>Is something like this feasibly possible in jQuery/javascript?</p>