5

I have a simple "async" JS function:

function asyncFunc(i) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}

if I want to execute this asyncFunc 5 times in a for loop, i.e. log 1 - 5 per second, and totally costs 5 seconds.

1

2

3

4

5

I know jQuery's when().done() can do that however if I am in a environment with NO 3rd party JS libraries, what is the simplest and elegant way to achieve this?

Actually for example I want to write a util function which accepts an array of async functions, and this util function can execute passed in functions one by one:

function execAsyncTasks([asyncTask1, asyncTask2, asyncTask3]) {
    asyncTask1();
    // Wait until asyncTask1 finished
    asyncTask2();
    // Wait until asyncTask2 finished
    asyncTask3();
    // Wait until asyncTask3 finished
}
Wayne Ye
  • 2,464
  • 3
  • 25
  • 29
  • you can give add a callback parameter to your async methods you call on timeout! – silly Nov 27 '12 at 11:33
  • The beginning of your post suggests that you want "time scheduling" and the later example suggest that you just want to perform tasks 1 after another?! – EricG Nov 27 '12 at 11:48
  • If each task has to wait until the previous one finishes, then they are not "stand alone" async task. You can just "wrap" them in a normal `for` and "asyncly" run the "wrapper" using your already-ready async method. – Passerby Nov 27 '12 at 11:59

4 Answers4

9

All your tasks will have to implement some sort of callback mechanism, because that's the only way you'll ever know that an asynchronous task has been completed. Having that, you could do something like:

function executeTasks() {
    var tasks = Array.prototype.concat.apply([], arguments);
    var task = tasks.shift();
    task(function() {
        if(tasks.length > 0)
            executeTasks.apply(this, tasks);
    });
}

executeTasks(t1, t2, t3, t4);

Demo

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
2

You can use Async module:

https://github.com/caolan/async

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

async.series([
    function(){ ... },
    function(){ ... }
]);
luin
  • 2,077
  • 2
  • 20
  • 23
0

This is one approach of many

function execAsyncTasks(asyncTask1, asyncTask2, asyncTask3) {
  var count = 0;

  function nextCommand() {
    switch (count) {
      case 0:
        asyncTask1();
        break;
      case 1:
        asyncTask2();        
        break;
      case 2:
        asyncTask3();
      default:
        return;
    }
    count++;
    setTimeout(nextCommand, 1000);
  }
  nextCommand();
}
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • The problem with this is that the count variable is incremented whether the function has finished or not. Ideally the asyncTask when completed would increment the count variable. – Bruno Nov 27 '12 at 11:50
  • Actually I was using one approach and I suppose is better than this one: – Wayne Ye Nov 27 '12 at 13:45
  • var counter = 0; for(var i = 0;i < 5;i++) { setTimeout(function () {}, counter++ * 1000); } – Wayne Ye Nov 27 '12 at 14:19
0

you can have a sync mechanism using callbacks and recursive function calls: see http://jsfiddle.net

function asyncFunc(i, callback) {
  setTimeout(function() {
    document.body.innerHTML += '<p>' + i + '</p>';
    callback();
  }, 1000);
}

var args = [0, 1, 2, 3, 4];

function loopThroughArgs(callback) {
  if (args.length == 0) {
    callback();
  } else {
    asyncFunc(args[0], function() {
      args.splice(0, 1); //remove the first item from args array
      loopThroughArgs(callback);
    });
  }
}

loopThroughArgs(function() {
  document.body.innerHTML += '<p>done !</p>';
});
Anshuman
  • 758
  • 7
  • 23
Alex Pacurar
  • 5,801
  • 4
  • 26
  • 33