├── index.js
├── package.json
├── LICENSE
├── README.md
├── test
└── basic.js
└── breathe.js
/index.js:
--------------------------------------------------------------------------------
1 | module.exports = require('./breathe.js');
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "breathejs",
3 | "version": "0.2.1",
4 | "description": "a library to write nonblocking, asynchronous JavaScript",
5 | "license": "BSD-3-Clause",
6 | "homepage": "https://breathejs.org",
7 | "author": {
8 | "name": "Steve Tung"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/breathejs/breathejs.git"
13 | },
14 | "devDependencies": {
15 | "mocha": "3.x"
16 | },
17 | "scripts": {
18 | "test" : "./node_modules/mocha/bin/mocha"
19 | }
20 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2016, Steve Tung
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without modification,
5 | are permitted provided that the following conditions are met:
6 |
7 | 1. Redistributions of source code must retain the above copyright notice, this
8 | list of conditions and the following disclaimer.
9 |
10 | 2. Redistributions in binary form must reproduce the above copyright notice,
11 | this list of conditions and the following disclaimer in the documentation
12 | and/or other materials provided with the distribution.
13 |
14 | 3. Neither the name of the copyright holder nor the names of its contributors
15 | may be used to endorse or promote products derived from this software without
16 | specific prior written permission.
17 |
18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # breathe.js
2 | Using breathe.js, you can easily write nonblocking JavaScript that runs in the main thread of a web page.
3 |
4 | ## How does it work? ##
5 | With **breathe.js**, you divide large, processor-intensive functions into smaller tasks that don't run all at once. The library offers a replacement to loops, function calls, and code blocks, automatically exiting a function after a certain amount of time and allowing the webpage to respond, before returning to the function.
6 |
7 | As a simple example, in traditional JavaScript, you may have a long looping function:
8 | ```js
9 | function longLoopingFunction() {
10 | var i;
11 | for(i = 0; i < 100000; i++) {
12 | trickyFunction();
13 | }
14 | }
15 | ```
16 |
17 | Here `trickyFunction()` runs 100,000 times, without letting any other code run or UI respond. But with breathe.js, the same code can be written as:
18 |
19 | ```js
20 | function breathableLongLoopingFunction() {
21 | return breathe.times(100000, function (i) {
22 | trickyFunction();
23 | });
24 | }
25 | ```
26 |
27 | Here the function also runs sequentially, but if it runs for too long (over 17 milliseconds by default), breathe.js relinquishes the main thread to allow other functions to run or UI to respond, then runs the remaining loop, repeatedly relinquishing if necessary.
28 |
29 | By using promise conventions and nested functions, [converting code](https://breathejs.org/Using-Breathe.html#Converting-Code) is usually straightforward, preserving a function's overall structure and logic. Converting code makes it asynchronous, and adds methods to stop, pause, and unpause the code. Read more about how to use it on the ['Using breathe.js' page](https://breathejs.org/Using-Breathe.html#Converting-Code).
30 |
31 | ## Can't Web Workers run nonblocking code? ##
32 | Web workers are designed to run asynchronous, nonblocking code (in another thread, to boot!), but unfortunately they can't do everything. Variables aren't easily shared with a page's main thread, instead relying on message passing. Workers can't acccess DOM, nor can most access a canvas (though there is an OffscreenCanvas in development). Since breathe.js can run inside the main thread of a page, it can access its variables, DOM, and canvases.
33 |
34 | Web workers still use a single thread within the worker, so a computation-heavy function can block other code— namely message handling— from running. Breathe.js works within web workers, so they can respond in the middle of executing a long-running function. It also makes it easy to pause and unpause code running within the worker.
35 |
36 | ## Some notes of warning ##
37 | * Even though breathe.js is wonderful, convenient, and easy-to-use, there are frequently better solutions than running computationally taxing code within the main thread of a client. Web workers, in particular, were created for true multithreaded processing. Or in some cases, you may want to move computation to a server.
38 | * Because breathe.js frees up blocking code, it doesn't usually trigger a web browser's frozen page warning. If there are parts that remain processor intensive, like an infinite loop of console.log statements or chunks that execute longer than expected, it can make the UI sluggish or nonresponsive. Without the warning, it can be more difficult to stop the page.
39 |
40 | ## How do I get started? ##
41 | Check out the ['Examples' page](https://breathejs.org/examples/index.html) to see what you can do with it, and read the ['Using breathe.js' page](https://breathejs.org/Using-Breathe.html) for an in-depth explanation.
42 |
43 | ## Creating breathable code
44 | Breathe.js currently offers three main ways to create breathable code. [`breathe.chain()`](#breathe-chain) creates a breathable promise chain. As an alternative to `while` loops, [`breathe.loop()`](#breathe-loop-config) creates an asynchronous loop, with a condition and a body. And [`breathe.times()`](#breathe-times-config) creates a loop with a fixed number of iterations and a body, a replacement for some `for` loops.
45 |
46 | ### The anatomy of a breatheable function
47 | Large functions can be subdivided into blocks of code, with variable declarations and synchronous and/or asynchronous code.
48 | ```js
49 | function () {
50 | var variablesSharedInsideOfThisBlock;
51 | synchronousCode();
52 | return asynchronousCode();
53 | }
54 | ```
55 |
56 | You don't need to have both synchronous code or asynchronous code, but asynchronous code usually involves subsequent code blocks. For instance, breathe.loop takes a body as an argument, which is a code block. This allows you to nest loops:
57 | ```js
58 | function nestedLoop() {
59 | var running;
60 | running = true;
61 | return breathe.loop(function () { return running; }, function () {
62 | // another code block
63 | var i;
64 | i = 0;
65 | return breathe.loop({ function () { return running && i++ < 50; },
66 | function () {
67 | running = doSomethingAwesome(c);
68 | }
69 | );
70 | }
71 | );
72 | }
73 | ```
74 |
75 | You can use the .then() method of promises (the asynchronous code) to chain code blocks together, so you can run code after asynchronous code completes.
76 | ```js
77 | function sequentialLoops() {
78 | var i = 0;
79 | return breathe.loop(function () { i++ < 50;}, function () {
80 | console.log('Counting up: ', i);
81 | }
82 | ).then(function () {
83 | // another code block
84 | return breathe.loop(function () { i-- >= 0;}, function () {
85 | console.log('Counting down: ', i);
86 | });
87 | });
88 | }
89 | ```
90 |
91 | ## **breathe.js** API
92 |
93 | ### # Breathable Chains
94 | **Breathable Chains** are similar to [traditional promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) in that they implement `then()` and `catch()` methods, though they return the original chain object rather than a new promise. _Breathable chains_ implement additional methods to stop, pause, and unpause promise chains.
95 |
96 | * # breathe.**chain**([*initValue*])
97 | * creates and returns a _breathable chain_, with a promise chain initialized to initValue.
98 |
99 | * # _breathableChain_.**then**(*onFulfilled*[, *onRejected*])
100 | * adds functions *onFulfilled* and *onRejected* to the promise chain, which are called when the promise is fulfilled or rejected. Similar to [`Promise.prototype.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), except it alters its internal promise chain instead of returning a new promise. Both *onFulfilled* and *onRejected* can optionally return a value to pass on to the next promise chain, or a promise (breathable or not), that are resolved or rejected before continuing down the promise chain. Returns the invoking _breathableChain_.
101 |
102 | * # _breathableChain_.**catch**(*onRejected*)
103 | * adds function *onRejected* to the promise chain, which is called when the promise is rejected. Similar to [`Promise.prototype.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch), except it alters its internal promise chain instead of returning a new promise. *onRejected* can optionally return a value to pass on to the next promise chain that are resolved or rejected before continuing down the promise chain. Returns the invoking _breathableChain_.
104 |
105 | * # _breathableChain_.**pause**()
106 | * requests _breathableChain_ to pause its current chain. Because not all promises in the chain may be pauseable, pausing may be delayed until the current promise resolves. Returns a promise that resolves when the current chain is paused.
107 |
108 | * # _breathableChain_.**unpause**()
109 | * requests _breathableChain_ to unpause its current chain. Returns a resolved promise.
110 |
111 | * # _breathableChain_.**stop**()
112 | * requests _breathableChain_ to stop its current chain. Because not all promises in the chain may be stoppable, stopping may be delayed until the current promise resolves. Returns a promise that resolves when the current chain is stopped.
113 |
114 | ### # Loops
115 | **Breathable Loops** are breathable chains that repeatedly iterate over a *body* while a *condition* is true. They can be stopped, paused, or unpaused. They can serve as a replacement to `while` loops.
116 | * # breathe.**loop**(*config*)
117 | * *config*.**condition** [required]
118 | * an argumentless function that should return false (or a falsey value) if the loop should exit
119 | * *config*.**body** [required]
120 | * a function that gets called for every iteration of the loop. It can optionally return a value; if it returns a promise or chain (breathable or traditional), the loop does not continue iterating until the promise or chain resolves.
121 |
122 | * # breathe.**loop**(*condition*, *body*, [*config*])
123 | * equivalent to calling breathe.loop, with *config.condition* and *config.body* set to *condition* and *body*
124 |
125 | ### # Special Loops
126 | **Times Loops** are breathable chains that repeatedly iterate over a *body* for a fixed number of *iterations*. They can be stopped, paused, or unpaused. They can serve as a replacement to some `for` loops.
127 | * # breathe.**times**(*config*)
128 | * *config*.**iterations** [required]
129 | * a value equal to the number of iterations of the loop.
130 | * *config*.**body** [required]
131 | * a function(iterationNumber) that gets called for every iteration of the loop. The first argument is the current iteration number (starting at 0). It can optionally return a value; if it returns a promise or chain (breathable or traditional), the loop does not continue iterating until the promise or chain resolves.
132 |
133 | * # breathe.**times**(*iterations*, *body*, [*config*])
134 | * equivalent to calling breathe.times, with *config.iterations* and *config.body* set to *iterations* and *body*
135 |
--------------------------------------------------------------------------------
/test/basic.js:
--------------------------------------------------------------------------------
1 | var assert = require('assert');
2 | var breathe = require('../breathe.js');
3 |
4 | var initValue = 'init value';
5 | var testValue = 'test value';
6 | var testErrorMessage = 'test error message';
7 | var testIterations = 11;
8 |
9 | var getMilliseconds = function () {
10 | var hrtime = process.hrtime();
11 | return hrtime[0] * 1000000 + hrtime[1] / 1000;
12 | };
13 |
14 | var delayedPromise = function (timeout, val) {
15 | return new Promise(function (resolve, reject) {
16 | setTimeout(function () {
17 | resolve(val);
18 | }, timeout);
19 | });
20 | };
21 |
22 | var blockingRecursiveChain = function (remaining, fn) {
23 | if (fn) {
24 | fn();
25 | }
26 | if (!remaining) {
27 | return breathe.chain();
28 | }
29 | var start = getMilliseconds();
30 | while (getMilliseconds() - start < 1) {
31 | // wait
32 | }
33 | return breathe.chain().then(function () {
34 | return blockingRecursiveChain(remaining - 1, fn);
35 | });
36 | };
37 |
38 | var blockingChain = function (time) {
39 | return breathe.chain(function (resolve, reject) {
40 | var i=0;
41 | var start = getMilliseconds();
42 | while (getMilliseconds() - start < time) {
43 | // wait
44 | i++;
45 | }
46 | resolve();
47 | });
48 | };
49 |
50 | describe('`breathe`', function () {
51 | beforeEach(function () {
52 | breathe.setBatchTime(17);
53 | });
54 | describe('`breathe.chain`', function () {
55 |
56 | it('should be able to resolve a value', function () {
57 | return breathe.chain(testValue).then(function (d) {
58 | assert.equal(d, testValue);
59 | });
60 | });
61 |
62 | it('should be able to resolve a promise', function () {
63 | return breathe.chain(Promise.resolve(testValue))
64 | .then(function (d) {
65 | assert.equal(d, testValue);
66 | });
67 | });
68 |
69 | it('should be able to resolve a pending promise', function () {
70 | return breathe.chain(delayedPromise(10, testValue))
71 | .then(function (d) {
72 | assert.equal(d, testValue);
73 | });
74 | });
75 |
76 | it('should not immediately resolve', function () {
77 | var c = initValue;
78 | var chain = breathe.chain(function (resolve, reject) {
79 | c = testValue;
80 | resolve();
81 | });
82 | assert.equal(c, initValue);
83 | return chain;
84 | });
85 |
86 | describe('`then`', function () {
87 | it('should be able to resolve a returned value', function () {
88 | return breathe.chain()
89 | .then(function () {
90 | return testValue;
91 | }).then(function (d) {
92 | assert.equal(d, testValue);
93 | });
94 | });
95 |
96 | it('should be able to resolve a returned promise', function () {
97 | return breathe.chain().then(function () {
98 | return Promise.resolve(testValue);
99 | }).then(function (d) {
100 | assert.equal(d, testValue);
101 | });
102 | });
103 |
104 | it('should be able to resolve a returned pending promise', function () {
105 | return breathe.chain().then(function () {
106 | return delayedPromise(10, testValue);
107 | }).then(function (d) {
108 | assert.equal(d, testValue);
109 | });
110 | });
111 |
112 | it('should be able to resolve a returned `breathe.chain`', function () {
113 | return breathe.chain().then(function () {
114 | return breathe.chain(testValue);
115 | }).then(function (d) {
116 | assert.equal(d, testValue);
117 | });
118 | });
119 |
120 | it('should relinquish the main thread when over batch time', function () {
121 | breathe.setBatchTime(5);
122 | var v = initValue;
123 | var d = blockingRecursiveChain(100);
124 | setTimeout(function () {
125 | v = testValue;
126 | }, 15);
127 | return d.then(function () {
128 | assert.equal(v, testValue);
129 | });
130 | });
131 |
132 | it('should not relinquish the main thread while under batch time', function () {
133 | breathe.setBatchTime(500);
134 | var v = initValue;
135 | var d = blockingRecursiveChain(100);
136 | setTimeout(function () {
137 | v = testValue;
138 | }, 15);
139 | return d.then(function () {
140 | assert.equal(v, initValue);
141 | });
142 | });
143 |
144 | it('should be able to catch thrown errors', function () {
145 | return breathe.chain(Promise.reject(testErrorMessage))
146 | .then(null, function (err) {
147 | assert.equal(testErrorMessage, err);
148 | });
149 | });
150 |
151 | it('should be able to catch thrown errors and then resolve values', function () {
152 | return breathe.chain(Promise.reject(testErrorMessage))
153 | .then(null, function (err) {
154 | return testValue;
155 | }).then(function (d) {
156 | assert.equal(d, testValue);
157 | });
158 | });
159 |
160 | it('should not catch errors thrown from the same `then` call', function () {
161 | var v = initValue;
162 | return breathe.chain()
163 | .then(function () {
164 | throw testErrorMessage;
165 | }, function (err) {
166 | assert(testErrorMessage !== err);
167 | }).then(null, function (err) {
168 | assert.equal(testErrorMessage, err);
169 | });
170 | });
171 | });
172 |
173 |
174 | describe('`catch`', function () {
175 |
176 | it('should be able to catch thrown errors', function () {
177 | return breathe.chain(Promise.reject(testErrorMessage))
178 | .catch(function (err) {
179 | assert.equal(testErrorMessage, err);
180 | });
181 | });
182 |
183 | it('should be able to resolve values', function () {
184 | return breathe.chain(Promise.reject(testErrorMessage))
185 | .catch(function (err) {
186 | return testValue;
187 | }).then(function (d) {
188 | assert.equal(d, testValue);
189 | });
190 | });
191 |
192 | });
193 | });
194 |
195 | describe('`breathe.loop`', function () {
196 |
197 | it('should repeat the body while the condition is true', function () {
198 | var i = 0;
199 | return breathe.loop(function () {
200 | return i < testIterations;
201 | }, function () {
202 | i++;
203 | }).then(function (d) {
204 | assert.equal(i, testIterations);
205 | });
206 | });
207 |
208 | it('can take a configuration object as an argument', function () {
209 | var i = 0;
210 | return breathe.loop({
211 | condition: function () {
212 | return i < testIterations;
213 | },
214 | body: function () {
215 | i++;
216 | }}).then(function (d) {
217 | assert.equal(i, testIterations);
218 | });
219 | });
220 |
221 |
222 | it('should not immediately run', function () {
223 | var i = 0, c = initValue;
224 | var loop = breathe.loop(function () {
225 | return i < testIterations;
226 | }, function () {
227 | i++;
228 | c = testValue;
229 | });
230 | assert.equal(c, initValue);
231 | return loop;
232 | });
233 |
234 | it('should wait for a returned promise to resolve before continuing', function () {
235 | var i = 0;
236 | var v = initValue;
237 | var iterations = 4;
238 | var timeout = 5;
239 | var t = getMilliseconds();
240 | return breathe.loop(function () {
241 | return i < iterations;
242 | }, function () {
243 | i++;
244 | assert.equal(v, initValue);
245 | v = testValue;
246 | return delayedPromise(timeout).then(function () {
247 | v = initValue;
248 | });
249 | }).then(function () {
250 | assert.equal(v, initValue);
251 | // may want to tweak reasonableTime if setTimeout isn't accurate
252 | var wiggleRoom = 3 / 4;
253 | var reasonableTime = (getMilliseconds() - t) > iterations * timeout * wiggleRoom;
254 | assert(reasonableTime);
255 | });
256 | });
257 |
258 | it('should relinquish the main thread when over batch time', function () {
259 | breathe.setBatchTime(5);
260 | var v = initValue;
261 | var i = 0;
262 | var ret = breathe.loop(function () {
263 | return i < 200;
264 | }, function () {
265 | i++;
266 | return blockingChain(1);
267 | });
268 | setTimeout(function () {
269 | v = testValue;
270 | }, 15);
271 | return ret.then(function () {
272 | assert.equal(v, testValue);
273 | });
274 | });
275 |
276 | it('should not relinquish the main thread while under batch time', function () {
277 | breathe.setBatchTime(500);
278 | var v = initValue;
279 | var i = 0;
280 | var ret = breathe.loop(function () {
281 | return i < 200;
282 | }, function () {
283 | i++;
284 | return blockingChain(1);
285 | });
286 | setTimeout(function () {
287 | v = testValue;
288 | }, 15);
289 | return ret.then(function () {
290 | assert.equal(v, initValue);
291 | });
292 | });
293 |
294 | it('should be able to throw errors', function () {
295 | var i = 0;
296 | return breathe.loop(function () {
297 | return i < 10;
298 | }, function () {
299 | i++;
300 | if (i === 4) {
301 | throw testErrorMessage;
302 | }
303 | }).then(function () {
304 | throw new Error('Loop should have thrown an error');
305 | }, function (err) {
306 | assert.equal(err, testErrorMessage);
307 | });
308 | });
309 |
310 | it('should be able to nest loops', function () {
311 | var counter = 0;
312 | var i, j;
313 | var outerLoopIterations = 6;
314 | var innerLoopIterations = 7;
315 | i = 0;
316 | return breathe.loop(function () {
317 | return i < outerLoopIterations;
318 | }, function () {
319 | i++;
320 | j = 0;
321 | return breathe.loop(function () {
322 | return j < innerLoopIterations;
323 | }, function () {
324 | j++;
325 | counter++;
326 | });
327 | }).then(function () {
328 | assert.equal(counter, outerLoopIterations * innerLoopIterations);
329 | });
330 | });
331 |
332 | describe('`then`', function () {
333 |
334 | it('should be able to resolve a value', function () {
335 | var i = 0;
336 | return breathe.loop(function () {
337 | return i < testIterations;
338 | }, function () {
339 | i++;
340 | }).then(function () {
341 | return i;
342 | }).then(function (d) {
343 | assert.equal(d, testIterations);
344 | });
345 | });
346 |
347 | it('should be able to resolve a promise', function () {
348 | var i = 0;
349 | return breathe.loop(function () {
350 | return i < testIterations;
351 | }, function () {
352 | i++;
353 | }).then(function () {
354 | return Promise.resolve(i);
355 | }).then(function (d) {
356 | assert.equal(d, testIterations);
357 | });
358 | });
359 |
360 | });
361 |
362 | });
363 |
364 | describe('`breathe.times`', function () {
365 | it('should repeat the body function for n iterations', function () {
366 | var i = 0;
367 | return breathe.times(testIterations, function () {
368 | i++;
369 | }).then(function (d) {
370 | assert.equal(i, testIterations);
371 | });
372 | });
373 |
374 | it('can take a configuration object as an argument', function () {
375 | var i = 0;
376 | return breathe.times({
377 | iterations: testIterations,
378 | body: function () {
379 | i++;
380 | }}).then(function (d) {
381 | assert.equal(i, testIterations);
382 | });
383 | });
384 |
385 | it('should pass the body function an incrementing, zero-based counter', function () {
386 | var previous;
387 | return breathe.times(testIterations, function (i) {
388 | if (previous === undefined) {
389 | assert.equal(0, i);
390 | } else {
391 | assert.equal(previous + 1, i);
392 | }
393 | previous = i;
394 | });
395 | });
396 |
397 | it('should not immediately run', function () {
398 | var c = initValue;
399 | var loop = breathe.chain(testIterations, function () {
400 | c = testValue;
401 | });
402 | assert.equal(c, initValue);
403 | return loop;
404 | });
405 |
406 | it('should wait for a returned promise to resolve before continuing', function () {
407 | var v = initValue;
408 | var iterations = 4;
409 | var timeout = 5;
410 | var t = getMilliseconds();
411 | return breathe.times(iterations, function () {
412 | assert.equal(v, initValue);
413 | v = testValue;
414 | return delayedPromise(timeout).then(function () {
415 | v = initValue;
416 | });
417 | }).then(function () {
418 | assert.equal(v, initValue);
419 | // may want to tweak reasonableTime if setTimeout isn't accurate
420 | var wiggleRoom = 3 / 4;
421 | var reasonableTime = (getMilliseconds() - t) > iterations * timeout * wiggleRoom;
422 | assert(reasonableTime);
423 | });
424 | });
425 |
426 | it('should relinquish the main thread when over batch time', function () {
427 | breathe.setBatchTime(5);
428 | var v = initValue;
429 | var ret = breathe.times(100, function () {
430 | return blockingChain(1);
431 | });
432 | setTimeout(function () {
433 | v = testValue;
434 | }, 15);
435 | return ret.then(function () {
436 | assert.equal(v, testValue);
437 | });
438 | });
439 |
440 | it('should not relinquish the main thread while under batch time', function () {
441 | breathe.setBatchTime(500);
442 | var v = initValue;
443 | var ret = breathe.times(100, function () {
444 | return blockingChain(1);
445 | });
446 | setTimeout(function () {
447 | v = testValue;
448 | }, 15);
449 | return ret.then(function () {
450 | assert.equal(v, initValue);
451 | });
452 | });
453 |
454 | it('should be able to throw errors', function () {
455 | return breathe.times(10, function (i) {
456 | if (i === 4) {
457 | throw testErrorMessage;
458 | }
459 | }).then(function () {
460 | throw new Error('breathe.times should have thrown an error');
461 | }, function (err) {
462 | assert.equal(err, testErrorMessage);
463 | });
464 | });
465 |
466 | it('should be able to nest loops', function () {
467 | var counter = 0;
468 | var outerLoopIterations = 6;
469 | var innerLoopIterations = 7;
470 | return breathe.times(outerLoopIterations, function (i) {
471 | return breathe.times(innerLoopIterations, function (j) {
472 | counter++;
473 | });
474 | }).then(function () {
475 | assert.equal(counter, outerLoopIterations * innerLoopIterations);
476 | });
477 | });
478 |
479 | describe('`then`', function () {
480 | it('should be able to resolve a value', function () {
481 | var i = 0;
482 | return breathe.times(testIterations, function () {
483 | i++;
484 | }).then(function () {
485 | return i;
486 | }).then(function (d) {
487 | assert.equal(d, testIterations);
488 | });
489 | });
490 | it('should be able to resolve a promise', function () {
491 | var i = 0;
492 | return breathe.times(testIterations, function () {
493 | i++;
494 | }).then(function () {
495 | return Promise.resolve(i);
496 | }).then(function (d) {
497 | assert.equal(d, testIterations);
498 | });
499 | });
500 | });
501 |
502 | });
503 | });
--------------------------------------------------------------------------------
/breathe.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) Steve Tung All Rights Reserved */
2 |
3 | (function (root, factory) {
4 | "use strict";
5 | var moduleName = 'breathe';
6 | if (typeof define === 'function' && define.amd) {
7 | define([], function () {
8 | return (root[moduleName] = factory(root));
9 | });
10 | } else if (typeof module === 'object' && module.exports) {
11 | module.exports = (root[moduleName] = factory(root));
12 | } else {
13 | root[moduleName] = factory(root);
14 | }
15 | }(this, function (exports) {
16 | "use strict";
17 |
18 | /***************************
19 | * Begin Immediate Promise
20 | ***************************/
21 | var promiseStates = {
22 | pending: 1,
23 | resolved: 2,
24 | rejected: 3
25 | };
26 | var isFunction = function (f) {
27 | return typeof f === 'function';
28 | };
29 | var isObject = function (o) {
30 | return typeof o === 'object';
31 | };
32 | var ImmediatePromise = function (fn) {
33 | var that = this;
34 | this.state = promiseStates.pending;
35 | this.immediate = ImmediatePromise.runImmediately;
36 |
37 | this._pendingThen = [];
38 | this._pendingCatch = [];
39 |
40 | this.resolve = function (value) {
41 | if (that.state !== promiseStates.pending) {
42 | return;
43 | }
44 | that.state = promiseStates.resolved;
45 | that._value = value;
46 | that._runFn(function () {
47 | that._clearResolvedQueue();
48 | });
49 | };
50 |
51 | this.reject = function (reason) {
52 | if (that.state !== promiseStates.pending) {
53 | return;
54 | }
55 | that.state = promiseStates.rejected;
56 | that._reason = reason;
57 | if (!that._pendingCatch.length && ImmediatePromise.loggingErrors) {
58 | that._loggingErrorTimeout = setTimeout(function () {
59 | console.warn(that._reason);
60 | }, ImmediatePromise.loggingErrorTimeout);
61 | }
62 | that._runFn(function () {
63 | that._clearRejectedQueue();
64 | });
65 | };
66 |
67 | fn.call(this, this.resolve, this.reject);
68 | };
69 |
70 |
71 | var _resolveValueOrPromise = function (that, d, resolve, reject) {
72 | var then;
73 | var thenableCalled = false;
74 | try {
75 | if (d === that) {
76 | reject(new TypeError("Recursive Promise Detected"));
77 | return;
78 | }
79 | then = d && d.then;
80 | if ((isObject(d) || isFunction(d)) && isFunction(then)) {
81 | then.call(d, function (val) {
82 | if (thenableCalled) {
83 | return;
84 | }
85 | if (d === val) {
86 | reject(new TypeError("Recursive Promise Detected"));
87 | return;
88 | }
89 | thenableCalled = true;
90 | _resolveValueOrPromise(that, val, resolve, reject);
91 | }, function (reason) {
92 | if (thenableCalled) {
93 | return;
94 | }
95 | thenableCalled = true;
96 | reject(reason);
97 | });
98 | } else {
99 | resolve(d);
100 | }
101 | } catch (e) {
102 | if (!thenableCalled) {
103 | reject(e);
104 | }
105 | }
106 | };
107 |
108 | ImmediatePromise.prototype = {
109 | _clearResolvedQueue: function () {
110 | while (this._pendingThen.length) {
111 | this._pendingThen.shift()(this._value);
112 | }
113 | },
114 | _clearRejectedQueue: function () {
115 | while (this._pendingCatch.length) {
116 | this._pendingCatch.shift()(this._reason);
117 | }
118 | },
119 | _runFn: function (fn) {
120 | if (this.immediate) {
121 | fn();
122 | } else {
123 | setTimeout(fn, 0);
124 | }
125 | },
126 | then: function (onResolved, onRejected) {
127 | var that = this;
128 | var p = {};
129 | p = new ImmediatePromise(function (resolve, reject) {
130 | var resolveValue = (that.state === promiseStates.rejected) ? null : function (value) {
131 | if (isFunction(onResolved)) {
132 | try {
133 | _resolveValueOrPromise(p, onResolved(value), resolve, reject);
134 | } catch (e) {
135 | reject(e);
136 | }
137 | } else {
138 | resolve(value);
139 | }
140 | };
141 |
142 | var catchReason = (that.state === promiseStates.resolved) ? null : function (reason) {
143 | if (isFunction(onRejected)) {
144 | try {
145 | _resolveValueOrPromise(p, onRejected(reason), resolve, reject);
146 | } catch (e) {
147 | reject(e);
148 | }
149 | } else {
150 | reject(reason);
151 | }
152 | };
153 |
154 | that._pendingThen.push(resolveValue);
155 | that._pendingCatch.push(catchReason);
156 | clearTimeout(that._loggingErrorTimeout);
157 | if (that.state === promiseStates.resolved) {
158 | that._runFn(function () {
159 | that._clearResolvedQueue();
160 | });
161 | } else if (that.state === promiseStates.rejected) {
162 | that._runFn(function () {
163 | that._clearRejectedQueue();
164 | });
165 | }
166 | });
167 | return p;
168 | },
169 | 'catch': function (onRejected) {
170 | this.then(null, onRejected);
171 | }
172 | };
173 |
174 | ImmediatePromise.resolve = function (d) {
175 | var p = new ImmediatePromise(function (resolve, reject) {
176 | _resolveValueOrPromise({}, d, resolve, reject);
177 | });
178 | return p;
179 | };
180 |
181 | ImmediatePromise.reject = function (e) {
182 | return new ImmediatePromise(function (resolve, reject) {
183 | reject(e);
184 | });
185 | };
186 |
187 | ImmediatePromise.version = '0.1.1';
188 |
189 | ImmediatePromise.loggingErrors = true;
190 | ImmediatePromise.loggingErrorTimeout = 3000;
191 | ImmediatePromise.runImmediately = true;
192 |
193 | ImmediatePromise.states = promiseStates;
194 |
195 | /**********************
196 | *
197 | * Begin breathe
198 | *
199 | **********************/
200 |
201 | var breathe = {
202 | version: '0.2.1'
203 | };
204 |
205 | /**********************
206 | * CONSTANTS
207 | **********************/
208 | var DEFAULT_BATCH_TIME = 17;
209 | var GENERAL_WORK_ID = -1;
210 |
211 | var STOP_MESSAGE = 'Stopped';
212 | breathe.STOP_MESSAGE = STOP_MESSAGE;
213 |
214 | var STATE_STARTING = 1;
215 | var STATE_RUNNING = 2;
216 | var STATE_PAUSING = 3;
217 | var STATE_PAUSED = 4;
218 | var STATE_UNPAUSING = 5;
219 | // There is no STATE_UNPAUSED, just STATE_RUNNING
220 | var STATE_STOPPING = 7;
221 | var STATE_STOPPED = 8;
222 | var STATE_FINISHED = 9;
223 |
224 | /**********************
225 | * Private Variables
226 | * (used throughout)
227 | **********************/
228 |
229 | var _batchTime = DEFAULT_BATCH_TIME;
230 | var _newWorkId = 2;
231 | var _currWorkId;
232 | var _inMainLoop = false;
233 |
234 |
235 | /**********************
236 | * Utility functions
237 | **********************/
238 |
239 | var timer = (typeof performance !== 'undefined' && performance.now ?
240 | performance : {
241 | now: function () {
242 | return new Date().getTime();
243 | }
244 | });
245 |
246 | var copyObj = function (from, to) {
247 | var key;
248 | if (from) {
249 | for (key in from) {
250 | if (from.hasOwnProperty(key)) {
251 | to[key] = from[key];
252 | }
253 | }
254 | }
255 | return to;
256 | };
257 |
258 | var breatheGate = function () {
259 | // this takes advantage that .resolve() and .reject() are exposed
260 | // in ImmediatePromise
261 | return new ImmediatePromise(emptyFn);
262 | };
263 |
264 | breathe.getBatchTime = function (time) {
265 | return _batchTime;
266 | };
267 |
268 | breathe.setBatchTime = function (time) {
269 | _batchTime = time;
270 | return breathe;
271 | };
272 |
273 | breathe.getCurrWorkId = function () {
274 | return _currWorkId;
275 | };
276 |
277 | var isThenable = function (t) {
278 | return t && typeof t.then === 'function';
279 | };
280 |
281 | var uniqueId = function () {
282 | return _newWorkId++;
283 | };
284 | breathe.uniqueId = uniqueId;
285 |
286 | var emptyFn = function () {};
287 |
288 | var passFn = function (o) {
289 | return o;
290 | };
291 |
292 | var resolveFunction = function (o) {
293 | return typeof o === 'function' ? resolveFunction(o()) : o;
294 | };
295 |
296 | breathe.setTimeout = function (t) {
297 | t = t || 0;
298 | return {
299 | prework: null,
300 | postwork: function (fn) {
301 | return setTimeout(fn, t);
302 | },
303 | timeout: function (fn) {
304 | return setTimeout(fn, t);
305 | },
306 | cancel: function (a) {
307 | return clearTimeout(a);
308 | }
309 | };
310 | };
311 | copyObj(breathe.setTimeout(), breathe.setTimeout);
312 |
313 | breathe.requestAnimationFrame = function () {
314 | return {
315 | prework: function (fn) {
316 | return requestAnimationFrame(fn);
317 | },
318 | postwork: null,
319 | timeout: function (fn) {
320 | return requestAnimationFrame(fn);
321 | },
322 | cancel: function (a) {
323 | return cancelAnimationFrame(a);
324 | }
325 | };
326 | };
327 | copyObj(breathe.requestAnimationFrame(), breathe.requestAnimationFrame);
328 |
329 | var _workTimeouter = breathe.setTimeout;
330 | var _workTimeoutRef;
331 |
332 | var switchTimeouter = function (timeouter, batchTime) {
333 | _workTimeouter.cancel(_workTimeoutRef);
334 | _workTimeouter = timeouter;
335 | if (batchTime !== undefined) {
336 | breathe.setBatchTime(batchTime);
337 | }
338 | if (!_inMainLoop || !_workTimeouter.postwork) {
339 | _workTimeouter.timeout(doSomeWork);
340 | }
341 | };
342 |
343 | breathe.animationMode = function () {
344 | return switchTimeouter(breathe.requestAnimationFrame, 12);
345 | };
346 |
347 | breathe.timeoutMode = function () {
348 | return switchTimeouter(breathe.setTimeout, DEFAULT_BATCH_TIME);
349 | };
350 |
351 | var _throttling = {};
352 | var breatheThrottle = function (id, amount) {
353 | _throttling[id] = amount;
354 | };
355 |
356 | breathe.throttle = function (id, amount) {
357 | if (id && id.getWorkId()) {
358 | breathe.throttle(id.getWorkId(), amount);
359 | } else {
360 | breatheThrottle(id, amount);
361 | }
362 | };
363 |
364 | var customHandlers = {};
365 | breathe.on = function (type, fn) {
366 | customHandlers[type] = customHandlers[type] || [];
367 | customHandlers[type].push(fn);
368 | };
369 | var trigger = function (type, data) {
370 | var i;
371 | var handlers = customHandlers[type];
372 | if (!handlers) {
373 | return;
374 | }
375 | for (i=0; i < handlers.length; i++) {
376 | if (data) {
377 | handlers[i].apply(this, data);
378 | } else {
379 | handlers[i]();
380 | }
381 | }
382 | };
383 |
384 | /**********************
385 | * Main loop
386 | **********************/
387 | var _preWorkQueue = [];
388 | var _workQueue = [];
389 | var _postWorkQueue = [];
390 | /**
391 | * One iteration of the main loop
392 | */
393 | var doSomeWork = function () {
394 | var start = timer.now();
395 | var ind;
396 | var id;
397 | var throttleCount = {};
398 | _inMainLoop = true;
399 | trigger('batchBegin');
400 | if (_workTimeouter.prework) {
401 | _workTimeoutRef = _workTimeouter.prework(doSomeWork);
402 | }
403 |
404 | // preWorkQueue is work that is always executed before a batch of work
405 | // usually adds work to the workQueue and calls event handlers
406 | for (ind = 0; ind < _preWorkQueue.length; ind++) {
407 | _currWorkId = _preWorkQueue[ind].id;
408 | _preWorkQueue[ind].warmup();
409 | }
410 | _preWorkQueue = [];
411 |
412 | // The workQueue is the main queue for running work. It sustains a loop by
413 | // the .work() function adding more items to the workQueue
414 | for (ind = 0; ind < _workQueue.length &&
415 | timer.now() - start < _batchTime; ind++) {
416 | id = _workQueue[ind].id;
417 | _currWorkId = id;
418 | if (_throttling[id]) {
419 | throttleCount[id] = (throttleCount[id] || 0) + 1;
420 | if (throttleCount[id] > _throttling[id]) {
421 | _workQueue[ind].cooldown();
422 | } else {
423 | _workQueue[ind].work();
424 | }
425 | } else {
426 | _workQueue[ind].work();
427 | }
428 | }
429 |
430 | // If a queue is not completed within a batch, run .cooldown() for the
431 | // remaining items. It usually adds work to the preWorkQueue
432 | // and calls event handlers.
433 | for (ind = ind; ind < _workQueue.length; ind++) {
434 | _currWorkId = _workQueue[ind].id;
435 | _workQueue[ind].cooldown();
436 | }
437 | _workQueue = [];
438 |
439 | for (ind = 0; ind < _postWorkQueue.length; ind++) {
440 | _currWorkId = _postWorkQueue[ind].id;
441 | _postWorkQueue[ind].cooldown();
442 | }
443 | _postWorkQueue = [];
444 | if (_workTimeouter.postwork) {
445 | _workTimeoutRef = _workTimeouter.postwork(doSomeWork);
446 | }
447 | _currWorkId = GENERAL_WORK_ID;
448 | trigger('batchEnd');
449 | _inMainLoop = false;
450 | };
451 | // Start the main loop, even though there are no items in any of the queues
452 | _currWorkId = GENERAL_WORK_ID;
453 | doSomeWork();
454 |
455 | var addPreWork = function (workObj) {
456 | _preWorkQueue.push(workObj);
457 | };
458 |
459 | var addWork = function (workObj) {
460 | _workQueue.push(workObj);
461 | };
462 |
463 | var queueWork = function (id, work) {
464 | var warmup = function () {
465 | addWork({
466 | work: work,
467 | cooldown: cooldown,
468 | id: id
469 | });
470 | };
471 | var cooldown = function () {
472 | addPreWork({
473 | warmup: warmup,
474 | id: id
475 | });
476 | };
477 | warmup();
478 | };
479 |
480 | breathe.queue = function (work) {
481 | queueWork(_currWorkId, work);
482 | return breathe;
483 | };
484 |
485 | var fnInContext = function (id, fn) {
486 | return function () {
487 | var prevId = _currWorkId;
488 | _currWorkId = resolveFunction(id);
489 | var r = fn.apply(this, arguments);
490 | _currWorkId = prevId;
491 | return r;
492 | };
493 | };
494 |
495 | var StateHandler = function () {
496 | this.state = STATE_STARTING;
497 | };
498 |
499 | StateHandler.prototype = {
500 | pause: function () {
501 | var that = this;
502 | if (this.state === STATE_PAUSED) {
503 | return ImmediatePromise.resolve();
504 | } else if (this.state === STATE_PAUSING) {
505 | return this.callGate;
506 | } else if (this.state === STATE_STOPPING) {
507 | return ImmediatePromise.reject("Can't Pause. Already Stopping.");
508 | } else if (this.state === STATE_STOPPED) {
509 | return ImmediatePromise.reject("Can't Pause. Already Stopped.");
510 | }
511 | this.state = STATE_PAUSING;
512 | var currVal = this.currVal;
513 | if (currVal && currVal.then && currVal.pause) {
514 | this.pauser = currVal;
515 | this.callGate = ImmediatePromise.resolve(currVal.pause())
516 | .then(function () {
517 | that.state = STATE_PAUSED;
518 | });
519 | } else {
520 | this.callGate = breatheGate();
521 | }
522 | return this.callGate;
523 | },
524 | unpause: function () {
525 | var gate;
526 | if (this.state === STATE_STOPPING) {
527 | return ImmediatePromise.reject("Can't Unpause. Already Stopping.");
528 | } else if (this.state === STATE_STOPPED) {
529 | return ImmediatePromise.reject("Can't Unpause. Already Stopped.");
530 | }
531 | this.state = STATE_RUNNING;
532 | if (this.pauseGate) {
533 | gate = this.pauseGate;
534 | this.pauseGate = null;
535 | gate.resolve();
536 | }
537 | if (this.pauser) {
538 | gate = this.pauser;
539 | this.pauser = null;
540 | return ImmediatePromise.resolve(gate.unpause());
541 | }
542 | return ImmediatePromise.resolve();
543 | },
544 | stop: function () {
545 | var that = this;
546 | var callGate;
547 | if (this.state === STATE_STOPPED) {
548 | return ImmediatePromise.resolve();
549 | }
550 | if (this.state === STATE_PAUSING) {
551 | this.callGate.reject("Pausing interrupted by stop.");
552 | }
553 | var currVal = this.currVal;
554 | if (currVal && currVal.then && currVal.stop) {
555 | this.state = STATE_STOPPING;
556 | callGate = ImmediatePromise.resolve(currVal.stop())
557 | .then(function () {
558 | that.state = STATE_STOPPED;
559 | });
560 | }
561 | if (this.state === STATE_PAUSED && this.pauseGate) {
562 | this.state = STATE_STOPPED;
563 | this.pauseGate.reject(STOP_MESSAGE);
564 | return ImmediatePromise.resolve();
565 | }
566 | this.state = STATE_STOPPING;
567 | this.callGate = callGate || breatheGate();
568 | return this.callGate;
569 | },
570 | gatesPromise: function (val) {
571 | var gate = this.callGate;
572 | if (this.state === STATE_RUNNING) {
573 | return val;
574 | } else if (this.state === STATE_STOPPING) {
575 | if (this.callGate) {
576 | this.callGate = null;
577 | gate.resolve();
578 | }
579 | this.state = STATE_STOPPED;
580 | return ImmediatePromise.reject(STOP_MESSAGE);
581 | } else if (this.state === STATE_PAUSING) {
582 | if (this.callGate) {
583 | this.callGate = null;
584 | gate.resolve();
585 | }
586 | this.state = STATE_PAUSED;
587 | this.pauseGate = breatheGate();
588 | return this.pauseGate;
589 | } else if (this.state === STATE_STOPPED) {
590 | return ImmediatePromise.reject(STOP_MESSAGE);
591 | } else if (this.state === STATE_PAUSED) {
592 | if (!this.pauseGate) {
593 | this.pauseGate = breatheGate();
594 | }
595 | return this.pauseGate;
596 | }
597 | return val;
598 | }
599 | };
600 |
601 | var breatheChain = function (init) {
602 | var endPromise = ImmediatePromise.resolve();
603 | var id = _currWorkId;
604 | var currVal;
605 | var stateHandler = new StateHandler();
606 |
607 | var atEnd = function() {
608 | return endPromise.state === promiseStates.resolved
609 | || endPromise.state === promiseStates.rejected;
610 | };
611 |
612 | var handleGates = function (val) {
613 | return stateHandler.gatesPromise(val);
614 | };
615 |
616 | var stateCommandWrapper = function (command) {
617 | return function () {
618 | var gate = stateHandler[command]();
619 | if (atEnd()) {
620 | endPromise = endPromise.then(handleGates);
621 | }
622 | return gate;
623 | };
624 | };
625 |
626 | var ret = {
627 | throttle: function (amount) {
628 | breatheThrottle(_id, amount);
629 | },
630 | pause: stateCommandWrapper('pause'),
631 | stop: stateCommandWrapper('stop'),
632 | unpause: stateCommandWrapper('unpause'),
633 | atEnd: atEnd,
634 | then: function (o, e) {
635 | endPromise = endPromise
636 | .then(handleGates)
637 | .then(!o ? null : function (val) {
638 | return new ImmediatePromise(function (resolve, reject) {
639 | queueWork(id, function () {
640 | ImmediatePromise.resolve()
641 | .then(handleGates).then(fnInContext(id, function () {
642 | try {
643 | currVal = o(val);
644 | stateHandler.currVal = currVal;
645 | resolve(currVal);
646 | } catch (e) {
647 | reject(e);
648 | }
649 | }));
650 | });
651 | });
652 | }, e ? fnInContext(id, e) : null)
653 | .then(handleGates);
654 | return ret;
655 | },
656 | getWorkId: function () {
657 | return id;
658 | }
659 | };
660 | ret['catch'] = function (e) {
661 | return ret.then(null, e);
662 | };
663 | ret.then(function () {
664 | stateHandler.state = STATE_RUNNING;
665 | currVal = typeof init === 'function' ? new ImmediatePromise(init) : init;
666 | stateHandler.currVal = currVal;
667 | return currVal;
668 | });
669 | return ret;
670 | };
671 | breathe.chain = breatheChain;
672 |
673 | var breatheLoop = function (config) {
674 | var _id = _currWorkId;
675 | config = config || {};
676 | var body = config.body;
677 | var condition = config.condition;
678 | var currVal = config.initVal;
679 | var stateHandler = new StateHandler();
680 | var retLoop = breatheChain(function (resolve, reject) {
681 | var workBit;
682 | var preworkBit;
683 | var work = function () {
684 | if (stateHandler.state === STATE_PAUSING) {
685 | stateHandler.state = STATE_PAUSED;
686 | stateHandler.pauseGate = breatheGate();
687 | stateHandler.pauseGate.then(function () {
688 | stateHandler.pauseGate = null;
689 | warmup();
690 | });
691 | stateHandler.callGate.resolve();
692 | stateHandler.callGate = null;
693 | return;
694 | } else if (stateHandler.state === STATE_STOPPING) {
695 | stateHandler.state = STATE_STOPPED;
696 | reject(STOP_MESSAGE);
697 | stateHandler.callGate.resolve();
698 | stateHandler.callGate = null;
699 | return;
700 | }
701 | try {
702 | if (!condition()) {
703 | resolve();
704 | return;
705 | }
706 | currVal = body();
707 | stateHandler.currVal = currVal;
708 | if (isThenable(currVal)) {
709 | currVal.then(function (v) {
710 | currVal = v;
711 | stateHandler.currVal = v;
712 | addWork(workBit);
713 | }, reject);
714 | } else {
715 | addWork(workBit);
716 | }
717 | } catch (e) {
718 | reject(e);
719 | }
720 | };
721 | var warmup = function () {
722 | if (config.onBatchBegin) {
723 | config.onBatchBegin();
724 | }
725 | addWork(workBit);
726 | };
727 | var cooldown = function () {
728 | if (config.onBatchEnd) {
729 | config.onBatchEnd();
730 | }
731 | addPreWork(preworkBit);
732 | };
733 | workBit = {
734 | work: work,
735 | cooldown: cooldown,
736 | id: _id
737 | };
738 | preworkBit = {
739 | warmup: warmup,
740 | id: _id
741 | };
742 | stateHandler.state = STATE_RUNNING;
743 | warmup();
744 | });
745 | retLoop.pause = function () {
746 | return stateHandler.pause();
747 | };
748 | retLoop.unpause = function () {
749 | return stateHandler.unpause();
750 | };
751 | retLoop.stop = function () {
752 | return stateHandler.stop();
753 | };
754 | return breatheChain(retLoop);
755 | };
756 |
757 | breathe.loop = function (condition, body, config) {
758 | var loopConfig;
759 | config = copyObj(config, {});
760 | if (arguments.length === 1) {
761 | loopConfig = arguments[0];
762 | } else {
763 | loopConfig = copyObj({
764 | condition: condition,
765 | body: body
766 | }, config);
767 | }
768 | return breatheLoop(loopConfig);
769 | };
770 |
771 | var breatheTimesLoop = function (config) {
772 | var timesConfig = copyObj(config, {});
773 | var body = config.body;
774 | var iterations = config.iterations;
775 | var i = 0;
776 | timesConfig = copyObj({
777 | condition: function () {
778 | return i < iterations;
779 | },
780 | body: function (val) {
781 | return body(i++, val);
782 | }
783 | }, timesConfig);
784 | return breatheLoop(timesConfig);
785 | };
786 |
787 | breathe.times = function (iterations, body, config) {
788 | var timesConfig;
789 | config = copyObj(config, {});
790 | if (arguments.length === 1) {
791 | timesConfig = arguments[0];
792 | } else {
793 | timesConfig = copyObj({
794 | iterations: iterations,
795 | body: body
796 | }, config);
797 | }
798 | return breatheTimesLoop(timesConfig);
799 | };
800 |
801 | /* experimental functions */
802 |
803 | breathe.stopChain = function (chain) {
804 | return breathe.chain(chain && chain.stop && chain.stop());
805 | };
806 |
807 | breathe.pauseChain = function (chain) {
808 | return breathe.chain(chain && chain.pause && chain.pause());
809 | };
810 |
811 | breathe.unpauseChain = function (chain) {
812 | return breathe.chain(chain && chain.unpause && chain.unpause());
813 | };
814 |
815 | var breatheTag = function (id) {
816 | if (id === undefined) {
817 | id = uniqueId();
818 | }
819 | var ret = {
820 | throttle: function (amount) {
821 | breatheThrottle(id, amount);
822 | return ret;
823 | },
824 | chain: fnInContext(id, breatheChain),
825 | loop: fnInContext(id, breathe.loop),
826 | times: fnInContext(id, breathe.times)
827 | };
828 | return ret;
829 | };
830 | breathe.tag = breatheTag;
831 | breathe.withId = breatheTag;
832 |
833 | return breathe;
834 | }));
--------------------------------------------------------------------------------