Angular2 setTimeout和cleartimeout动态/多个

时间:2018-03-12 18:25:34

标签: javascript angular settimeout cleartimeout

public timerId;

delete(id){
   this.timerId=id;
   this.timerId = setTimeout(()=>{
  //some logic
  },5000);
}

undo(id){
  this.timerId  = id;
  clearTimeout(this.timerId);
}

我想删除多个ID并使用延迟撤消(clearTimeout特定)id。使用此逻辑但无需帮助。 Angular2

1 个答案:

答案 0 :(得分:1)

也许你可以使用Observable:

private subscriptions = {};

public delete(id) {
    const subscription = Observable.of(null)
        .delay(5000)
        .subscribe(() => {
            // logic here
        });
    this.subscriptions[id+''] = subscription;
}

public undo(id) {
    const subscription = this.subscriptions[id+'']
    if (subscription && !subsciption.isUnsubscribed) {
        subscription.unsubscribe();
    }
    this.subscriptions[id+''] = null;
}