Angular2中的setTimeout返回ZoneTask而不是“数字”

6

我想在Angular2中使用setTimeout函数,并且我希望稍后能够清除这个定时器。

但是Angular2返回的是一个"ZoneTask"对象,而不是一个数字。

constructor() {
    this.name = 'Angular2'
    this.timeoutId = setTimeout(() => {  
      console.log('hello');
    }, 2000);


    console.log("timeout ID---", this.timeoutId); // Output - ZoneTask {_zone: Zone, runCount: 0, _zoneDelegates: Array[1], _state: "scheduled", type: "macroTask"…}_state: "notScheduled"_zone: Zone_zoneDelegates: nullcallback: function () {cancelFn: nulldata: Objectinvoke: function () {runCount: 0scheduleFn: function scheduleTask(task) {source: "setTimeout"state: (...)type: "macroTask"zone: (...)__proto__: ZoneTask app.ts:24

  }

我该如何使用普通的setTimeout函数?或者在Angular2中,有什么更好的方式来使用setTimeout以及clearTimeout呢?

这里是Plunkr链接


1
尝试使用 clearTimeout(this.timeoutId); 而不带第一个参数,或者您可以通过使用 this.timeoutId.data.handleId 获取 id。 - yurzui
是的,但为什么我得到了一个ZoneTask?我如何使用正常的settimeout! - Ajey
1个回答

7

更新

发布 zone@0.8.18 (2017-09-27)

计时器:修复#314,setTimeout / interval应返回原始timerId (#894)(aec4bd4)

之前的版本

您需要调用

clearTimeout(this.timeoutId);

您可以通过调用 timeoutId 来获取超时ID。
this.timeoutId.data.handleId

如果您希望使用本地的setTimeout,则可以利用以下方法:

this.timeoutId = window['__zone_symbol__setTimeout'](() => {  
  console.log('hello');
}, 2000); // setTimeout will work, but it returns ZoneTask

console.log("timeout ID---", this.timeoutId);
window['__zone_symbol__clearTimeout'](this.timeoutId); // clearTimeout will also work

但我不明白为什么你希望这样做。

谢谢您的解释。基本上您是说我不需要担心ZoneTask,只需像在JavaScript中一样使用clearTimeout即可? - Ajey
是的,你不需要担心这个。 - yurzui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接