Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an integer from setTimeout in Nodejs?

Tags:

People also ask

How do I get setTimeout to return value?

To get return value from setTimeout with JavaScript, we can create a promise from the setTimeout code. const x = () => { const promise = new Promise((resolve, reject) => { window. setTimeout(() => { resolve("done!"); }); }); return promise; }; const y = async () => { const result = await x(); console. log(result); };

Does setTimeout work in node js?

setTimeout is a built-in Node. js API function which executes a given method only after a desired time period which should be defined in milliseconds only and it returns a timeout object which can be used further in the process.

What is the return type of setTimeout?

The Return Type for setTimeout() in Typescript # log('success'); }, 1500); console. log(timeout); The ReturnType utility type allows us to construct a type that consists of the return type of the passed in function.


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?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!