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?