0

I try to store Date.now() after a setIntervall invoked a callback. After that, I'd like to clear the intervall, so it only fires once. All that in a class. But the variable I store the intervalID in and I hoped would be available "class-wide" keeps "undefined". I am pretty sure I am doing sth awfully wrong with JS scope, but I cannot find out what.

class Signal {
    t : number;
    private intervallId : number | undefined;
    
    
    constructor(t : number) {
        this.t = t;
              
    }

    wait() {
        
        this.intervallId = setInterval(this.signalTriggered, this.t)
        console.log("Never executed.")
    }

    signalTriggered() {
        const triggerTime : number = Date.now()
        console.log(this.intervallId) /* always undefined */
        if (this.intervallId) {clearInterval(this.intervallId)
        console.log(triggerTime); }
    }
}

var timer = new Signal(2000)
    timer.wait()
    console.log("Done.") /* Never printed out. */
Manticor
  • 3
  • 1
  • I cannot reproduce *`console.log("Never executed.")`* or *`/* Never printed out. */`*. But yes, `this` in your callback is not bound to the `timer` instance. – Bergi Sep 25 '22 at 21:13
  • "*I'd like to clear the intervall, so it only fires once*" - then use `setTimeout`, not `setInterval`! – Bergi Sep 25 '22 at 21:14

1 Answers1

0

The problem is the reference of the this, you are losing the original reference of it when passing the method as an argument to setIterval.
You could use an arrow function to wrap the method:

setInterval(() => this.signalTriggered(), this.t)

Or use Function.prototype.bind to assign the reference of this:

setInterval(this.signalTriggered.bind(this), this.t)
Xion 14
  • 427
  • 2
  • 8