Permalink
Browse files

Adds .timeout support.

  • Loading branch information...
1 parent 3203a1b commit 0bf32b5e9c8e85f422108a1026d2bb22b178f854 Chakrit Wichian committed Mar 11, 2013
Showing with 49 additions and 4 deletions.
  1. +19 −2 lib/jam.js
  2. +30 −2 test/helpers.js
View
@@ -12,8 +12,9 @@ module.exports = (function() {
function replaceHead(args, newHead) {
args = toArgs(args);
+ if (!args.length) return [newHead];
- if (args.length) args[0] = newHead; else args.push(newHead);
+ args[0] = newHead;
return args;
}
@@ -22,6 +23,10 @@ module.exports = (function() {
assert(typeof func === 'function', argName + ' argument missing or not a function');
};
+ function ensureNum(num, argName) {
+ assert(typeof num === 'number', argName + ' argument missing or not a number');
+ };
+
function ensureArray(arr, argName) {
assert(arr && typeof arr === 'object' && typeof arr.length === 'number',
argName + ' argument missing or does not looks like an array');
@@ -132,8 +137,20 @@ module.exports = (function() {
};
};
- // TODO: noError() ? or absorbError()
+ // ## jam.timeout( timeout )
+ // Pauses the chain for the specified `timeout` using `setTimeout`. Useful for
+ // inserting a delay in-between a long jam chain.
+ func.timeout = function(timeout) {
+ ensureNum(timeout, 'timeout');
+
+ return function(next) {
+ var args = replaceHead(arguments, null);
+ setTimeout(function() { next.apply(this, args); }, timeout);
+ };
+ };
+
+ // TODO: noError() ? or absorbError()
return func;
};
View
@@ -5,8 +5,9 @@
var assert = require('chai').assert
, stub = require('sinon').stub;
- var NON_FUNCTIONS = [undefined, null, 123, 'string']
- , NON_ARRAYS = [undefined, null, 123, { }, function() { }];
+ var NON_FUNCTIONS = [undefined, null, 123, 'string', { }, []]
+ , NON_ARRAYS = [undefined, null, 123, 'string', { }, function() { }]
+ , NON_NUMS = [undefined, null, 'string', { }, function() { }, []];
describe('Helpers', function() {
@@ -150,6 +151,33 @@
});
}); // .map
+ describe('.timeout function', function() {
+ it('should be exported', function() {
+ assert.typeOf(this.jam.timeout, 'function');
+ });
+
+ it('should throws if timeout argument missing or not a number', function() {
+ var me = this;
+
+ NON_NUMS.forEach(function(thing) {
+ assert.throws(function() { me.jam.timeout(thing); }, /timeout/i);
+ });
+ });
+
+ it('should calls the next function after the specified timeout', function(done) {
+ this.jam(this.jam.timeout(1))(done);
+ });
+
+ it('should forwards arguments to `next()` from previous function', function(done) {
+ this.jam(this.jam.return('hello'))
+ (this.jam.timeout(1))
+ (function(e, hello) {
+ assert(hello === 'hello');
+ done()
+ });
+ });
+ });
+
});
})();

0 comments on commit 0bf32b5

Please sign in to comment.