TypeScript: Abort or cancel a scheduled function

I would like to begin a repeating check until a certain condition is true, so that an event occurs only once after the check passes.

Currently my code looks like this:

Time.scheduleRepeating(() => {
    if (a == b) {
        Debug.log("IT HAS HAPPENED...");
        // CANCEL THIS REPEATING SCHEDULE
    }
}, 0);

So my ideal setup would be, after the message is printed to the log, the repeating schedule is cancelled so that it doesn’t spam the log.

Equally important, I also have the task of cancelling a scheduled function before it executes. For example:

let timedPlatform = Scene.getItem("A1B2C3");

timedPlatform.onCollisionEnter((collider) => {
    Time.schedule(() => {
       Debug.log("Stop standing on me!");
    }, 5);
});
timedPlatform.onCollisionExit((collider) => {
    // CANCEL THE ABOVE TIMED SCHEDULE
});

Unfortunately there seems to be no mention in the API page on how to cancel a repeating schedule.

What is the proper way to cancel a schedule, both non-repeating and repeating?

Have you tried break?

schedule and scheduleRepeating return Dispose object which it meant for such use cases (docs).

For example for the second part of your question you can use something like that:

class PlatformNotificator {
    private disposables: Map<String, Disposable> = new Map()

    onCollisionEnter(collider: BaseItem): void {
        let disposable = Time.schedule(() => {
            Debug.log("Stop standing on me!");
        }, 5);
        this.disposables[collider.id] = disposable

    }

    onCollisionExit(collider: BaseItem): void {
        let disposable = this.disposables[collider.id]
        if (disposable) {
            disposable.dispose()
            this.disposables.delete(collider.id)
        }
    }
} 
let notificator = new PlatformNotificator()
timedPlatform.onCollisionEnter(notificator.onCollisionEnter);
timedPlatform.onCollisionExit(notificator.onCollisionExit);

Note, that I didn’t test it, but this should give you an idea.

For the first part I would recommend you to take a look at observer pattern. Using scheduleRepeating for checking state change is error prone, inefficient and not extensible.

3 Likes

This is very helpful, thank you so much!

I’ll definitely take a look into these types of things, it’s definitely in my interests to make my code work better!