title: JQuery AJAX call function running twice
body: <p>EDIT: Unfortunately the answers and suggestions have not quite fixed the issue. I may have to switch to a "view more posts" button rather than using the scroll as I see this as the problem. Would be great to finally get a solution to this though as I can't find one anywhere.</p>
  
  <p>My solution was to add a timeout event. Terrible and dirty. this: </p>
  
  <pre><code>complete: function (data) {
      setTimeout(function() {
          $("#loading-posts").fadeOut("fast");
          $isFetchingNotes = false;
      }, 1000);
  }   
  </code></pre>
  
  <p>I written a custom blog for my website. As the user scrolls, older posts appear and load automatically through JQuery AJAX. This is working - however, it appears to be fetching the data 2, 3 or 4 more times than I want it to. I only want it to fetch the data once in fact. 
  So I put an "is running" type variable in, but that's not working either and it still fetches the data more than once and duplicates the post. Here is my code:</p>
  
  <pre><code>$(window).scroll(function(){
  
      var $scroll = $(window).scrollTop();
      var $docHeight = $(document).height();
      var $winHeight = $(window).height();
      var $lastPost = ($(".note-area:last").attr("id") - 1);
  
      if($scroll === $docHeight - $winHeight) {
  
          if(!$isFetchingNotes) {
  
              var $isFetchingNotes = true;
  
              $("div.more-posts").show();
              $("#loading-posts-gif").fadeIn("slow");
  
              $.ajax({
                  type: "GET",
                  url: 'loadnotes.php" ?&gt;',
                  data: { 
                      'lastPost': $lastPost
                  },
                  cache:true,
                  success: function(data) {
                      if(data) {
  
                          $('div#post-area').append(data);
                          $('div.more-posts').hide();
  
                      } else {
                          $('div.more-posts').replaceWith("&lt;h4&gt;-- End of notes --&lt;/h4&gt;");
                      }
                  },
                  complete: function () {
                      $("#loading-posts").fadeOut("fast");
                  }   
              }).error(function (event, jqXHR, ajaxSettings, thrownError) {
                  $('div.more-posts').html("&lt;h2&gt;Could not retrieve data&lt;/h2&gt;");
              });
  
              $isFetchingNotes = false;
  
          } // End if $isfetchingnotes
  
      } // End if scroll load point
  
  }); // End onscroll event
  </code></pre>
  
  <p>Can anyone please shed some light on why it may be trying to keep fetching the data despite the $isFetchingNotes variable being set to true? Thank you!</p>