dtech
dtech

Reputation: 14060

Executing a timeout prior to the defined delay

Say I have the following JavaScript code (in global context):

var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout

One can now cancel the set timeout:

clearTimeout(t);

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();

or

executeAndClearTimeout(t); // Does this one?

Upvotes: 2

Views: 81

Answers (3)

Paul
Paul

Reputation: 27423

On the server side, node.js setTimeout provides more of a object than an id. This is undocumented territory, I think.

Of course, using these internals might be hazardous in the sense that they could change as node develops.

node
> function x(){ console.log("hello"); }
> z = setTimeout(x,100000)
{ _idleTimeout: 100000,
  _onTimeout: [Function: x],
  _idlePrev: 
   { repeat: 100,
     _idleNext: [Circular],
     _idlePrev: [Circular],
     callback: [Function] },
  _idleNext: 
   { repeat: 100,
     _idleNext: [Circular],
     _idlePrev: [Circular],
     callback: [Function] },
  _idleStart: Thu, 18 Aug 2011 11:11:48 GMT }
> 

looks like you could just save z._onTimeout, clear the Timeout, and call _onTimeout --- but as I said, might break some day.

Also, nodeJS timeouts dont always fire when they should, but can be aligned to your CPUHZ grid.... if you are running linux with 100hz, you get 10ms resolution. I've seen them fire either early or late, in comparison with timers provided by hrtime.

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318498

No, that'ns ot possible.

However, you could write a wrapper for setTimeout and clearTimeout to achieve such a behaviour.

Upvotes: 0

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10636

I don't think such a function exists... but you're allready saving t, why not save f as well?

Upvotes: 1

Related Questions