0

I have a JavaScript class that has to publish events every so often. The code looks like this :

class TimerService {
  constructor(BroadcastService) {
    this.Broadcast = BroadcastService;
    this.timeout;
    this.warningTimer;
    this.startTimer();
  }

  startTimer() {
    clearTimeout(this.timeout);
    clearTimeout(this.warningTimer);
    this.timeout = setTimeout(this.startWarning, 30000);
  }

  startWarning() {
    this.Broadcast.send("timeout-warning");
    this.warningTimer = setTimeout(this.logout, 60000);
  }

  logout() {
    this.Broadcast.send("session-expired");
  }
}

export default { service: TimerService, name: "TimerService" };

The issue is, in the setTimeout calllback functions, the this scope points to window so I am not able to access this.Broadcast. What is the best way to structure this so I have access to everything I need?

erichardson30
  • 4,984
  • 8
  • 26
  • 47

1 Answers1

6

You can use these 2 approaches. I think first is the best if you have nothing to do with function own context and it is more preferable approach.

1) Arrow function - this.timeout = setTimeout(() => this.startWarning(), 30000);

2) Explicit Context binding - this.timeout = setTimeout(this.startWarning.bind(this), 30000);

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112