Permalink
Browse files

timeouts

  • Loading branch information...
1 parent 0d32d15 commit 6454ab0c05a63e15d6b1df2f22b6e8db9c5e17cb @substack committed Jan 14, 2012
Showing with 74 additions and 16 deletions.
  1. +32 −0 example/http.js
  2. +0 −13 example/simple.js
  3. +42 −3 index.js
View
@@ -0,0 +1,32 @@
+var toss = require('../');
+var http = require('http');
+
+var t = toss(2000, function (err) {
+ console.log('timed out');
+});
+
+function get (cb) {
+ http.get({ port : 8800, path : '/' }, function (res) {
+ res.on('end', cb);
+ });
+}
+
+function ready () {
+ get(t(function () {
+ get(t(function () {
+ console.log('finished');
+ t.end();
+ }));
+ }));
+}
+
+var server = http.createServer(function (req, res) {
+ setTimeout(function () {
+ res.end('beeeeeeeeeeeeeeeeeeeeeeeeep');
+ }, 600);
+});
+server.listen(8800, ready);
+
+setTimeout(function () {
+ server.close();
+}, 2000);
View
@@ -1,13 +0,0 @@
-var toss = require('../');
-var http = require('http');
-
-var t = toss();
-var to = setTimeout(function () {
- t.end();
-}, 1000);
-
-http.get({ port : 8800, path : '/' }, t(function (res0) {
- http.get({ port : 8800, '/beep' }, t(function (res1) {
- t.end();
- }));
-}));
View
@@ -1,7 +1,46 @@
-module.exports = function () {
+module.exports = function (outerTimeout, errCb) {
+ if (typeof outerTimeout === 'function') {
+ errCb = outerTimeout;
+ outerTimeout = 0;
+ }
+
+ if (outerTimeout) {
+ var oto = setTimeout(function () {
+ alive = false;
+ if (errCb) errCb(new Error('timeout'));
+ }, outerTimeout);
+ }
+
var alive = true;
- var self = function (fn) {
- if (alive) fn()
+ var self = function (timeout, fn) {
+ if (typeof timeout === 'function') {
+ fn = timeout;
+ timeout = 0;
+ }
+
+ if (!alive) {
+ var err = new Error('timeout');
+ return function () {
+ err.arguments = [].slice.call(arguments);
+ if (errCb) errCb(err)
+ };
+ }
+ if (alive && timeout) {
+ var err = new Error('timeout');
+ var ito = setTimeout(function () {
+ alive = false;
+ if (errCb) errCb(err);
+ }, timeout);
+ return function () {
+ clearTimeout(ito);
+ if (alive) fn.apply(this, arguments);
+ };
+ }
+ else if (alive) {
+ return function () {
+ if (alive) fn.apply(this, arguments);
+ };
+ }
};
self.end = function () {

0 comments on commit 6454ab0

Please sign in to comment.