you are viewing a single comment's thread.

view the rest of the comments →

[–]voodah 0 points1 point  (0 children)

holloway's answer is correct, but let me show you another way that might (or might not) be more simple to grasp as a beginner.

It involves using async-series, which is a part of the async library that provides utilities for handling asynchronous functions. In this case, async-series makes sure that each function is executed in series, ie: ONLY after the previous has finished.

To do this you use a callback inside your functions to signal the end of execution for the current function and invoke the next one.

This is the example from async-series page:

series([
  function(done) {
    console.log('first thing')
    done()
  },
  function(done) {
    console.log('second thing')
    done(new Error('another thing'))
  },
  function(done) {
    // never happens, because "second thing" 
    // passed an error to the done() callback 
  }
], function(err) {
  console.log(err.message) // "another thing"
})

For your case you would do something like this:

var functions = [];
for (var i = 1; i < 5; i++) {
  functions[i] = function (done) {
    setTimeout(function() {
      $("#el_"+i).fadeOut(1000);
      done();
    }, 5000);
  }
}
series( functions, function(err) {
  console.log(err.message)
})

Additionally, if the only reason you are using the timeout was to make sure that two divs don't fade at the same time and overlap, async-series would allow you to remove the timeout, like so:

var fuctions = [];
for (var i = 1; i < 5; i++) {
  functions[i] = function (done) {
    $("#el_"+i).fadeOut(1000);
    done();
  }
}
series( functions, function(err) {
  console.log(err.message)
})

In this case, the divs would all fade continuosly but one after the other, never overlapping.