ajax - How to refactor the javascript code when sleep like functionality needed? -


i see there lot's of threads here in asking javascript sleep function , know can done using settimeout , setinterval.

i userscripting greasemonkey , written script loads lot of pages , calculates them. works, don't want request pages fast.

var html0=syncget(url0); // custom function sync ajax call. // fill array for(var i=0;i<something.length;i++) {    // calculate url1,url2 using array , variable    // lots of local variables    var html1=syncget(url1);    // put sleep here.    // results    var html2=syncget(url2);    // put sleep here.    // results    // url3 page loaded url2    var html3=syncget(url3);    // put sleep here.    // results } // use result of loop , lots of code follow... 

the actual code bit more complex , longer this.

i'm crying nonexistent sleep function (and understand why not possible) how refactor use settimeout, setinterval functions , keep readable (and working) too?

i had similar problem big loop blocking whole browser in older browsers, solved using :

function handlenext(idx,length) {     idx++      //do stuff here base on idx.       if (idx < length) {         settimeout(function(){handlenext(idx,length)},1)     } else {         initsuccessend()     } }  var ln = something.length;   if (ln>0) {     handlenext(0,ln); } else {     initsuccessend() } 

here initsuccessend callback function called when finished ..


Comments