How can I get an integer from setTimeout in Nodejs?

The documentation on Timers for nodejs says that setTimeout will return a timeoutId http://nodejs.org/api/timers.html#timers_cleartimeout_timeoutid

When I use javascript in a web broswer, then I get an integer as a return value.

var b = setTimeout(function(){console.log("Taco Bell")})
// b = 20088

When I use node and do the same thing, the return is

var b = setTimeout(function(){console.log("Taco Bell")})
// { _idleTimeout: 60000,
//   _idlePrev: 
//     { _idleNext: [Circular],
//       _idlePrev: [Circular],
//       ontimeout: [Function] },
//   _idleNext: 
//     { _idleNext: [Circular],
//       _idlePrev: [Circular],
//       ontimeout: [Function] },
//   _onTimeout: [Function],
//   _idleStart: Wed Jan 30 2013 08:23:39 GMT-0800 (PST) }

What I would like to do is store the setTimeout integer into redis and then clear it later. So I try to do something like this

var redis = require('redis');
var redisClient = redis.createClient();
var delay = setTimeout(function(){console.log("hey")}, 20000);
var envelope  = { 'body' : 'body text', 'from' : 'test@test.com', 'to' : 'test@test.com', 'subject' : 'test subject', 'delay' : delay };
redisClient.hset("email", JSON.stringify(envelope), redis.print);

But then I get an error from JSON.stringify about not being able to handle Circular Objects. Is there a way to either have setTimeout return the ID or store enough of the object into redis to be able to clear later?

I would wrap the call to setTimeout into a function that stores the result of setTimeout in an object, so you can retrieve the timeout by their id.

something like this:

var timeouts = {};
var counter = 0;

function setTimeoutReturnsId(callback, delay) {
  var current = counter++;
  timeouts[current] = setTimeout(function() {
      timeouts[current] = null;
      callback();
    }, delay);
  return current;
}

function getTimeoutFromId(id) {
  return timeouts[id];
}

of course, when your node server restart, you'd need to clear redis, though.

I really wasn't believing that in nodejs(which I'm so in love)you would be forced to make such functions.

Fortunately there is an undocumented method on setTimeout's return(setInterval also has it!) called close

var timer = setInterval(doSomething, 1000);
setTimeout(function() {
    // delete my interval
    timer.close()
}, 5000);

Hope it be useful