0

I'm relatively new to typescript.
I'm trying to create a timer (or use a ready to use one if you know any) that will allow me to perform an operation several times (For example: Perform a UI operation like fade on every element in an array) every interval and will give me an end sign I can wait on.
So far I came with:

function delay(delay: number) {
    return new Promise(r => {
        setTimeout(r, delay);
    })
}

type timerCallback = (args: any, counter: number) => void;

class Timer {
    private _callback: timerCallback;

    constructor(callback: timerCallback) {
        this._callback = callback;
    }

    async doTimer(args: any, counter: number = 3, delayMs: number = 1000) {
        for (let i = 0; i < counter; i++) {
            await delay(delayMs);
            counter = counter - 1;
            this._callback(args, i);
            //console.log(this.counter);
        }
    }
}

And I use it like that:

public myMethod(): void {
// Show the players in the quality group
let showTimer: Timer = new Timer(this.showElement);
showTimer.doTimer(allQaulityGroupPlayersCells, allQaulityGroupPlayersCells.length, 750);
}

But I need to wait until all the iterations on the timer are over...
Any idea how can I achieve this?

1 Answer 1

1

Wait for the promise from showTimer.doTimer to settle, eithe rusing await (in an async function) or its then/catch methods (in a non-async function).

Your myMethod is a non-async function, so:

showTimer.doTimer(/*...*/)
.then(() => {
    // It's done now
})
.catch(() => {
    // An error occurred
});

Your doTimer's promise will never be rejected, so technically you could leave off the catch handler. But so many times you see people leaving it off when the promise may, in fact, be rejected that I'm hesitant to show an example that doesn't follow the Rule Of Promises: Thou Shalt Return The Promise Chain Or Handle Rejections. ;-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.