How to run javascript functions in sequence and waiting until each function finish -


basically, have 3 functions, , want run theses 3 functions in sequence (synchronous) , each function wait previous function finish. i've put timeout within functions simulate time execution, don't know if works. code is.

//my 3 functions... function wait1() {     settimeout(function(){         console.log('hello, function 1');         return 'ok';     },2000) }  function wait2() {     settimeout(function(){         console.log('hello, function 2');         return 'ok';     },2000) }  function wait3() {     settimeout(function(){         console.log('hello, function 3');         return 'ok';     },2000) }  var tasks = [wait1,wait2,wait3]; var counter = 0;  function iteratetasks(tasks) {     runsequence(tasks[counter], function(){         counter++;         if(counter < tasks.length) {             iteratetasks(tasks);         }     }); }  //@params func   received function //@params cb   received callback function function runsequence(func,cb) {     var timeout = 0;     var tmr = setinterval(function(){         if(func() === 'ok' || timeout === 5000) {             console.log('ok, func = ', func);             cb();             clearinterval(tmr);              timeout = 0;         }         timeout += 500;     },500); }  //start program... iteratetasks(tasks); 

appreciate help!

try add callback each function:

//my 3 functions... function wait1(callback) {     settimeout(function(){         console.log('hello, function 1');         callback('ok');     },2000) }  function wait2(callback) {     settimeout(function(){         console.log('hello, function 2');         callback('ok');     },2000) }  function wait3(callback) {     settimeout(function(){         console.log('hello, function 3');         callback('ok');     },2000) }  var tasks = [wait1,wait2,wait3]; var counter = 0;  function iteratetasks(tasks, callback) {     settimeout(function req(){         tasks[counter++](function(value) {             if (counter == tasks.length) {                 if (typeof callback == 'function') {                     callback();                 }             } else if (value === 'ok') {                 settimeout(req, 500);             }         });     }, 500); }  //start program... iteratetasks(tasks); 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -