Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

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

  • Loading branch information...
commit d8ad8204e5fa1e16a8c3ed0a0fcce8c039a33b03 1 parent 5ca4f25
@fblee fblee authored
View
11 public/javascripts/underscore_extensions.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);
+ }
+ });
}
});
View
34 spec/javascripts/lib/underscore_extensions_spec.js
@@ -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
+ });
+ });
});
Please sign in to comment.
Something went wrong with that request. Please try again.