1
0

nthen.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Caleb James DeLisle
  3. * Sat Mar 23 01:42:29 EDT 2013
  4. * Public Domain
  5. */
  6. ;(function() {
  7. var nThen = function(next) {
  8. var funcs = [];
  9. var timeouts = [];
  10. var calls = 0;
  11. var abort;
  12. var waitFor = function(func) {
  13. calls++;
  14. return function() {
  15. if (func) {
  16. func.apply(null, arguments);
  17. }
  18. calls = (calls || 1) - 1;
  19. while (!calls && funcs.length && !abort) {
  20. funcs.shift()(waitFor);
  21. }
  22. };
  23. };
  24. waitFor.abort = function () {
  25. timeouts.forEach(clearTimeout);
  26. abort = 1;
  27. };
  28. var ret = {
  29. nThen: function(next) {
  30. if (!abort) {
  31. if (!calls) {
  32. next(waitFor);
  33. } else {
  34. funcs.push(next);
  35. }
  36. }
  37. return ret;
  38. },
  39. orTimeout: function(func, milliseconds) {
  40. if (abort) { return ret; }
  41. if (!milliseconds) { throw Error("Must specify milliseconds to orTimeout()"); }
  42. var cto;
  43. var timeout = setTimeout(function() {
  44. while (funcs.shift() !== cto) ;
  45. func(waitFor);
  46. calls = (calls || 1) - 1;
  47. while (!calls && funcs.length) { funcs.shift()(waitFor); }
  48. }, milliseconds);
  49. funcs.push(cto = function() {
  50. for (var i = 0; i < timeouts.length; i++) {
  51. if (timeouts[i] === timeout) {
  52. timeouts.splice(i, 1);
  53. clearTimeout(timeout);
  54. return;
  55. }
  56. }
  57. throw new Error('timeout not listed in array');
  58. });
  59. timeouts.push(timeout);
  60. return ret;
  61. }
  62. };
  63. return ret.nThen(next);
  64. };
  65. if (typeof(define) == 'function') {
  66. // AMD (require.js etc)
  67. define([], function() { return nThen; });
  68. } else if (typeof(window) !== 'undefined') {
  69. // Browser global var nThen
  70. window.nThen = nThen;
  71. }
  72. if (typeof(module) !== 'undefined' && module.exports) {
  73. // Node.js
  74. module.exports = nThen;
  75. }
  76. })();