How can I get an integer from setTimeout in Nodejs?

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

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

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

When I use node and do the same, return

 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 save the setTimeout integer in redis and then clear it later. So I'm trying 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 a JSON.stringify error message stating that you cannot handle Circular Objects. Is there a way for setTimeout to return an identifier or save enough of an object in redis so that it can be cleared later?

+6
source share
2 answers

I would wrap the setTimeout call in a function that stores the result of setTimeout in the object, so you can get a timeout by their identifier.

something like that:

 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 you restart the node server, you will need to clear redis.

+1
source

I really did not believe that in nodejs (which I love so much) you would be forced to perform such functions.

Fortunately, there is an undocumented method when returning setTimeout (setInterval also has it!) Called close

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

Hope this will be helpful

0
source

All Articles