Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How can I get an integer from setTimeout in Nodejs?

How can I get an integer from setTimeout in Nodejs?

Problem

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' : '[email protected]', 'to' : '[email protected]', '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?

Problem courtesy of: earlonrails

Solution

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.

Solution courtesy of: Pascal Belloncle

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How can I get an integer from setTimeout in Nodejs?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×