javascript:如何验证计时器属性?

发布于 2024-09-14 17:56:04 字数 204 浏览 1 评论 0原文

如果我有以下代码:

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

我可以使用 t 中存储的 id 来验证计时器的持续时间和回调吗?我试图直接验证计时器的属性,因此我不必实际运行它,直到单元测试超时。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鯉魚旗 2024-09-21 17:56:04

不行,做不到。

相反,您可以做的是以不同的方式跟踪它们,如下所示:

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);
}

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);
}
飘落散花 2024-09-21 17:56:04

返回的 ID 是浏览器内部的,因此您不能用它做太多事情。但是,由于您知道启动计时器时的持续时间和回调,因此您也可以将整个事情包装在一个为您完成所有操作的 Timer 类中:

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();
}

然后您只需创建计时器并访问它们的属性,例如这:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文