Javascript calling so fast
<p>I have an annoying little issue here.  I have code which loads content from page2 and appends it to <code>#content</code>. That works, but sometimes it happens twice, then appends page3 before page2.  Thats because in page3, there is just one post, but in page2, 4 posts.</p>

<p>How can I make my code wait until the append finishes to run again? Here's my code:</p>

<pre><code>$(window).scroll(
  function(){
    if(browserName != "safari") {
      var curScrollPos = $('html').scrollTop();
    }
    else {
      var curScrollPos = $('body').scrollTop();
    }

    if(curScrollPos &gt; 218) {
      $("#sidebar").addClass("open");
    }

    if(curScrollPos &lt; 218) {
      $("#sidebar").removeClass("open");
    }

    var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

    if(scrollBottom == 0) {
      if(home != 0 || search != 0 || category != 0) { 
        if(currentPage &lt; numPages) {
          $("#main .loader-posts").fadeIn();
          currentPage++;

          if(search == 1) {
            var getPostsUrl = "page/"+currentPage+"/?s="+searchTerm;
          }
          else {
            var getPostsUrl = "page/"+currentPage;
          }

          $.get(getPostsUrl, function(data) {
                  $("#main .loader-posts").fadeOut(
                    'slow',
                    function(){
                      var newPosts = $(data).find("#content").html();
                      $("#content").append(newPosts);
                      $('#container.tiles').masonry('reload');
                    });
                });
        }
      }
      else {

      }
   }
</code></pre>
