0

I'm experimenting a bit with AJAX and have successfully deployed a simple AJAX A-synced function, yet when I'm changing it to use callback method - suddenly, it takes ages to load (about 10 - 15 mins...). Here's the function that executes right away:

function ajaxf() {
var xmlhttp;
  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200 && document.getElementById("icons")==null)
    {
    document.getElementById("text-12").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","http://some-url/ajax.php",true);
  xmlhttp.send();
} 

And here's the way slower iteration using a callback function:

function ajaxf(url,cfunc) {

  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=cfunc;
  xmlhttp.open("GET",url,true);
  xmlhttp.send();
}
document.body.onscroll = function ajaxb() {
  ajaxf("http://some-url/ajax.php",function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200 && document.getElementById("icons")==null)
    {
    document.getElementById("text-4").innerHTML=xmlhttp.responseText;
    }
  });
} 

Other (perhaps) relevant details - the ajax.php file weighs merely 532 B, on my local test server both run more or less equally the same, the first function uses onscroll="ajaxf()" inside the body tag...

I was under the impression AJAX would be a little more snappy???

  • 3
    You are firing off a request on scroll. Put a `console.log()` in there to see how often that fires. – Jasen Feb 04 '15 at 23:48
  • You will be getting a zillion onscroll events. The slowness is probably because of the huge number of ajax requests you are launching. – jfriend00 Feb 05 '15 at 00:05
  • 1
    Here is how to defer the scroll callback: http://stackoverflow.com/questions/27007957/jquery-resize-scroll-good-practice-to-use-variables/27008629#27008629 – istos Feb 05 '15 at 00:54
  • Thanks for the tips guys, with your help I was able to sort it out... for the sake of future reference I'll write my conclusions as an answer. –  Feb 05 '15 at 10:27

1 Answers1

0

I solved it, thanks to @jasen's tip I've put a console.log() and was able to see the scroll function fiered a gazillion times just like @jfriend00 said. Initially, I thought that by putting "document.getElementById("icons")==null" as a condition - the function would only fire once but I was wrong of course,

So the solution was / is: to reset the onscroll action after the first execution by adding "document.body.onscroll = null;" at the end of the function.