nl_tokens: * @method lazy ( [ ms ] = 1 [ limit ] = Infinity ) @returns Function @short Creates a lazy function that when called repeatedly will queue execution and wait [ ms ] milliseconds to execute again . @extra Lazy functions will always execute as many times as they are called up to [ limit ] after which point subsequent calls will be ignored ( if it is set to a finite number ) . Compare this to %throttle% which will execute only once per [ ms ] milliseconds . %lazy% is useful when you need to be sure that every call to a function is executed but in a non - blocking manner . Calling %cancel% on a lazy function will clear the entire queue . Note that [ ms ] can also be a fraction . @example
pl_tokens: function ( ms , limit ) { var fn = this , queue = [ ] , lock = false , execute , rounded , perExecution , result ; ms = ms || 1 ; limit = limit || Infinity ; rounded = ceil ( ms ) ; perExecution = <mask> ( rounded / ms ) || 1 ; execute = function ( ) { if ( lock || queue . length == 0 ) return ; // Allow fractions of a millisecond by calling // multiple times per actual timeout execution var max = math . max ( queue . length - perExecution , 0 ) ; while ( queue . length > max ) { // Getting uber-meta here... result = Function . prototype . apply . apply ( fn , queue . shift ( ) ) ; } setDelay ( lazy , rounded , function ( ) { lock = false ; execute ( ) ; } ) ; lock = true ; } function lazy ( ) { // The first call is immediate, so having 1 in the queue // implies two calls have already taken place. if ( ! lock || queue . length < limit - 1 ) { queue . push ( [ this , arguments ] ) ; execute ( ) ; } // Return the memoized result return result ; } return lazy ; }