Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 setTimeout returning ZoneTask rather than a "Number"

Trying to use setTimeout in angular2 and I want to clear the timeout later.

But Angular2 is returning a "ZoneTask" rather than a number

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

  }

How do I use the normal setTimeout or what is the preferred to use setTimeout and then clearTimeout in Angular2?

Plunkr here

like image 853
Ajey Avatar asked Mar 14 '17 12:03

Ajey


1 Answers

Update

Relase [email protected] (2017-09-27)

timer: fix #314, setTimeout/interval should return original timerId (#894) (aec4bd4)

Previous version

You need to call

clearTimeout(this.timeoutId);

The timeoutId you can get by calling

this.timeoutId.data.handleId

If you wish to use native setTimeout then you can leverage something like this:

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

But i don't understand why you wish that

like image 52
yurzui Avatar answered Sep 20 '22 00:09

yurzui