1

For some weird reason the ajax function below is firing twice. The loadMoreResults(); function is used to retrieve data from server. I tracked the data sent to the server using google developer tool it showed that the ajax request was fired twice in a row. I guess this happens when the user scroll fast.

 //Executed when user has scrolled bottom of the page
$(window).scroll(function (e) {
 if ($(window).scrollTop() == $(document).height() - $(window).height()) {
    loadMoreResults();
 }
 });

Any idea on how to prevent this from happening? Appreciate your help.

2 Answers 2

5

As you said, it could be because the user is scrolling too fast and the document does not get to be updated with the new results.

Try using a flag that will prevent calling the loadMoreResults() while the function is still executing.

You set it to true when the function starts and at the end, after you get your results, you set it to false. The check of the flag can be placed right at the beginning of the loadMoreresults() function, before setting the flag to true.

eg:

function loadMoreResults() {
  if (flag) return;
  flag = true;
[...]
  flag = false;
}
Sign up to request clarification or add additional context in comments.

Comments

0

For some reason I can't figure out. Setting a flag wasn't working for me. The function call would fire twice still. I had to use a timeout in my success callback

.then(function(resp) {
  var i, len, ref, t;
  ref = resp.data.users;
  for (i = 0, len = ref.length; i < len; i++) {
    t = ref[i];
    $scope.users.push(t);
  }

  return setTimeout((function() {
    if (resp.data.users.length > 0) {
      return $scope.busy = false;
    }
  }), 500);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.