jquery - JavaScript Function Queue -


i have ton of functions need run in succession, not before other has completed. need way queue these functions run after previous function completed. ideas?

function1(); function2(); function3(); function4(); function5(); 

you use this:

var functionqueue = (function(){     var queue = [];     var add = function(fnc){         queue.push(fnc);     };     var gonext = function(){         var fnc = queue.shift();         fnc();     };     return {         add:add,         gonext:gonext     }; }()); 

and use this:

var fnc1 = function(){     window.settimeout(function(){         alert("1 done");         functionqueue.gonext();     }, 1000); };  var fnc2 = function(){     window.settimeout(function(){         alert("2 done");         functionqueue.gonext();     }, 5000); };  var fnc3 = function(){     window.settimeout(function(){         alert("3 done");         functionqueue.gonext();     }, 2000); };  functionqueue.add(fnc1); functionqueue.add(fnc2); functionqueue.add(fnc3); functionqueue.gonext(); 

edit after few years: way people approaching pass in next function can call continue chain. so:

var queue = function(arr){     var index = 0;     var next = function(){         if (index >= arr.length) {return;}         arr[index++](next);     };     return next; };  var fn1 = function(next){     console.log("i fn1");     next(); };  var fn2 = function(next){     console.log("i fn2");     settimeout(next,1000); };  var fn3 = function(next){     console.log("i fn3");     settimeout(next,3000); };  var fn4 = function(next){     console.log("i fn4");     settimeout(next,1000); };  queue([fn1, fn2, fn3, fn4])(); 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -