1

I have an ajax call and would like to recall it once I finish parsing and animating the result into the page. And that's where I'm getting stuck.

I was able to recall the function, but it seems to not take into account the delays in the animation. i.e. The console keeps outputting the values at a wild pace.

I thought setInterval might help with the interval being the sum of the length of my delays, but I can't get that to work...

function loadEm(){
    var result=new Array();     
    $.getJSON("jsonCall.php",function(results){
        $.each(results, function(i, res){
            rand = (Math.floor(Math.random()*11)*1000)+2000;
            fullRand += rand;
            console.log(fullRand);
            $("tr:first").delay(rand).queue(function(next) {
            doStuff(res);
                next();
            });
        });
        var int=self.setInterval("loadEm()",fullRand);
    });
  }
});

1 Answer 1

3
  1. use setTimeout. setInterval will call again... and again... and again...

  2. use var fullRand at the top of loadElm (or inside the JSON callback). Without it you will increment the same global variable each time loadElm is called. In fact, you should use var with all your local variables -- that includes rand here. The Jibbering JavaScript Closure Notes covers variables and much more.

  3. use setTimeout(loadElm, fullRand) -- don't use a string in the first parameter :) See the MDC setTimeout documentation.

  4. Check for JavaScript errors (keep firebug/IE developer tools/the error console handy)

  5. Instead of using setTimeout, consider keeping count of how many of the animations have finished vs. how many total have finished! Imagine this:

===

// closure in JSON callback. see Jibbering notes.
var count = 0
$.each(results, function(i, res) {
  var rand = (Math.floor(Math.random()*11)*1000)+2000
  count++ // have to do action
  $("tr:first").delay(rand).queue(function(next) {
    ...
    count-- // action done
    if (!count) { // means count == 0 here :-) then...
      loadElm() // ...all actions done
    }
  })
})
if (!count) {
  // err... no animations started :(
}

Happy coding.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'll implement it and let you know!

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.