简体   繁体   中英

Javascript Recursion

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. ie 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM