Jerzy Gruszka Jerzy Gruszka - 2 months ago 6
TypeScript Question

Proceed to next step only when function has been run 10 times

I have this function:

function setIntervalX(callback, delay, repetitions): Promise<any> {

let promises = [];

var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
promises.push(new Promise((resolve, reject) => {});
}
}, delay);
return Promise.all(promises);
}


My goal is to call a function in test and the after those 10 calls have ended, I want to call expect in my function. So that means I have to wait for it to end, like this:

setIntervalX(() => {

//logic here

}, 1000, 10).then(() => {
expect(something).toBe(anotherThing);
});


I feel that my way of doing this is ugly, and can be done bettery. Any suggestions?

Answer

Unless you need the individual promises (you never use them above except in Promise.all), just use a single promise:

function setIntervalX(callback, delay, repetitions): Promise<any> {
    return new Promise(resolve => {
        let x = 0;
        let intervalID = window.setInterval(function () {
            callback();
            if (++x === repetitions) {
                window.clearInterval(intervalID);
                resolve();
            }
        }, delay);
    });
}
Comments