Permalink
Browse files

Add the ability to run functions in sequence, deferring each function

  • Loading branch information...
1 parent 5ca4f25 commit d8ad8204e5fa1e16a8c3ed0a0fcce8c039a33b03 @fblee fblee committed Feb 10, 2012
Showing with 45 additions and 0 deletions.
  1. +11 −0 public/javascripts/underscore_extensions.js
  2. +34 −0 spec/javascripts/lib/underscore_extensions_spec.js
@@ -267,6 +267,17 @@
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
+ },
+
+ deferInSequence: function (functions) {
+ var funcs = _.clone(functions);
+
+ return _.defer(function () {
+ if (funcs[0]) {
+ funcs.shift().apply();
+ return _.deferInSequence(funcs);
+ }
+ });
}
});
@@ -1,3 +1,4 @@
+/*global window */
describe("_.", function () {
describe("andand", function () {
@@ -127,4 +128,37 @@ describe("_.", function () {
});
});
});
+
+ describe("deferInSequence", function () {
+ var a;
+ beforeEach(function () {
+ a = 0;
+ });
+
+ function first() {
+ a += 10;
+ }
+ function second() {
+ a *= 5;
+ }
+ function third() {
+ a += 10;
+ }
+ it("should run all functions", function () {
+ expect(a).toBe(0);
+ _.deferInSequence([first, second, third]);
+ expect(a).toBe(0); // they should run deferred
+
+ window.setTimeout(function () {
+ expect(a).toBe(60);
+ }, 10); // arbitrary longish delay
+ });
+
+ it("should run the sequence in the correct order", function () {
+ _.deferInSequence([second, first, third]);
+ window.setTimeout(function () {
+ expect(a).toBe(20);
+ }, 10); // arbitrary longish delay
+ });
+ });
});

0 comments on commit d8ad820

Please sign in to comment.