nl_tokens: runArray () - dispatch an array of callbacks ( with a parallel run limit ) and run a callback when complete {{{ Internal function to run an array of functions ( usually in parallel ) Functions can be run in series by passing limit = 1 NOTE : Since this function is the central bottle - neck of the application code here is designed to run as efficiently as possible . This can make it rather messy and unpleasent to read in order to maximize thoughput . Series execution can be obtained by setting limit = 1
pl_tokens: function runArray ( tasks , limit , callback ) { var self = this ; var nextTaskOffset = 0 ; var running = 0 ; var err ; // Empty if ( ! tasks || ! tasks . length ) return callback ( ) ; // Timeout functionality {{{ var _timeoutTimer ; var resetTimeout = function ( setAgain ) { if ( _timeoutTimer ) clearTimeout ( _timeoutTimer ) ; if ( setAgain ) _timeoutTimer = self . _options . timeout ? setTimeout ( self . _options . timeoutHandler . bind ( self ) , self . _options . timeout ) : null ; } ; // }}} var taskFinish = function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; -- running ; if ( err && ! running ) { resetTimeout ( false ) ; callback ( err ) ; } else if ( err ) { // Has an err - stop allocating until we empty resetTimeout ( false ) ; // Pass } else if ( ! running && nextTaskOffset > tasks . length - 1 ) { // Finished everything resetTimeout ( false ) ; callback ( err ) ; } else if ( nextTaskOffset < tasks . length ) { // Still more to alloc running ++ ; resetTimeout ( true ) ; setTimeout ( tasks [ nextTaskOffset ++ ] . bind ( this . _context , taskFinish ) ) ; } } ; var maxTasks = limit && limit <= tasks . length ? <mask> : tasks . length ; for ( var i = 0 ; i < maxTasks ; i ++ ) { running ++ ; setTimeout ( tasks [ i ] . bind ( this , taskFinish ) ) ; } resetTimeout ( true ) ; // Start initial timeout nextTaskOffset = maxTasks ; return this ; }