views:

21

answers:

2

If I have the following code:

var myfunc = function() { alert('wow'); };
var t=setTimeout(myfunc, 300);

Is there anything I can do with the id stored in t to verify the timer's duration and callback? I'm trying to verify the timer's properties directly so I don't have to actually run it 'till timeout in my unit tests.

A: 

Nope, can't be done.

What you can do instead is track them differently, something like this:

var timeouts = [{
  fn: myfunc,
  timeout: 300
}];

for(var i = 0; i < timeouts.length; i++){
  timeouts[i].id = window.setTimeout(timeouts[i].fn, timeouts[i].timeout);
}
jvenema
A: 

The returned ID is internal to the browser, so you can't do much with it. But since you know the duration and callback when you initiate the timer, you could just as well wrap the whole thing in a Timer class that does everything for you:

function Timer(callback, timeout) {
  this.callback = callback;
  this.timeout = timeout;
  this.id = window.setTimeout(callback, timeout);
}

Timer.prototype.cancel = function() {
  window.clearTimeout(this.id);
}

Timer.prototype.fire = function() {
  this.cancel();
  this.callback();
}

Then you just create timers and access their properties like this:

t = new Timer(myfunc, 300);
alert(t.timeout);
casablanca