Whats the proper way to handle events / callbacks on a timer?

This is where my knowledge of TS/JS is a little weak, I’m looking for the proper way to bind an event or a call back to know when this timer is finished, at first I was thinking of having a isActive() but I know there’s better ways.:

class Timer extends StackPanel{
        isActive = true;
        constructor(i) {
            super();
            var textBlock = new myTextBlock(<string>new String(i));

            var handle = window.setInterval(() => {
                if (!GameSystem.GameControls.isPaused) {
                    i--;
                    textBlock.text = <string>new String(i)

                    if (i === 0) {
                        window.clearInterval(handle);
                        this.isActive = false;
                        this.dispose();
                    }
                }

            }, 1000);
        }
    }

Would it be best for me to pass a function an invoke it when the timer is done?

Something like that?

class Timer extends StackPanel{
        isActive = true;
        constructor(i: string, onTimerCallback: () => void) {
            super();
            var textBlock = new myTextBlock(<string>new String(i));

            var handle = window.setInterval(() => {
                if (!GameSystem.GameControls.isPaused) {
                    i--;
                    textBlock.text = <string>new String(i)

                    if (i === 0) {
                        window.clearInterval(handle);
                        this.isActive = false;
                        onTimerCallback()
                        this.dispose();
                    }
                }

            }, 1000);
        }
    }
1 Like

Awesome, thank you would that be the best way to handle a timer? Or is there better ways? In C# I would register a listener.

As there is no official way this one is fine :slight_smile:
Maybe you want to check promise for an even cleaner way?

That should be good, just wanted to make sure I had the right idea, thank you!

1 Like