Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning "this" when the function performs a setTimeout.

Status
Not open for further replies.

slobad23

IS-IT--Management
Jun 30, 2006
90
GB
I have a function that was taken from Nicholas Zakas named "Chunk". When it does it take an array, a function to invoke on each item of the array and a callback to run when complete.

JavaScript:
//array: the array of items on which to iterate. 
//process: a function which takes a single item (from the array).
//callback: function to carry out when all array items processed. 
//config: {object}
//  time: milliseconds for timeout period (default: 50). 
//  context: object on which to invoke "process" (default: null/global).
function chunk(array, process, callback, config) {
  //Create local copy of array. We will be altering this through .shift()
  //and don't want to alter the array parameter directly. 
  var items = array.concat();
  //Provide defaults for config object in case it has not been passed
  //or certain values don't exist on the object. 
  var time = config.time ? config.time : 50;
  var context = config.context ? config.context : null;
  
  var that = this;
  //Initial call to snippet which will process a single item from the array. 
  setTimeout(function snippet() {
    //Get first item from the queue. 
    var item = items.shift();
    //Invoke the process function on the context provided (or default).
    process.call(context, item);
    //If there are any more items, queue up the process for the next item.
    if (items.length)
      setTimeout(snippet, time)
      //When complete, invoke the callback function provided. 
    else {
      callback();
	}
  }, time);
}

What I would like to do, it to be able to chain another method to the end after the callback to avoid pyramid code.

Rather than:

chunk(a,
function() {},
function() {
chunk(a,
function() {},
function() {},
{});
},
{});

I would like to do this:

chunk(....).chunk(....).chunk(....);

I can't do this as it invokes the second and third immediately due to the setTimeouts in the chunk function. What I would really like to do is return this only when the setTimeout has completed all it's work. Any ideas on this?

"It doesn't do anything"

"Correction, it DOES nothing
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top