Typescript Loop with Delay

柔情痞子 提交于 2019-12-25 04:46:18

问题


I'm trying to create a metronome with Typescript.

I have this javascript code:

(function theLoop (i) {
        setTimeout(function () {
            metronome.play();
            if (--i) {
                theLoop(i);
            }
        }, 3000);          // interval set to 3000
    })(10);                // play it 10 times

And I wanted to convert it into Typescript code. Unfortunately I don't know how to do this (espacially regarding the last line => })(10);

Can someone help me with this?


回答1:


As everyone said, typescipt is a superset of javascript so your code is valid typescript, but here's how to do it with an arrow function (which is also es6 javascript) and types:

(function theLoop (i: number) {
        setTimeout(() => {
            metronome.play();
            if (--i) {
                theLoop(i);
            }
        }, 3000);
    })(10);

(code in playground)

And here's another variation:

let theLoop: (i: number) => void = (i: number) => {
    setTimeout(() => {
        metronome.play();
        if (--i) {
            theLoop(i);
        }
    }, 3000);
};

theLoop(10);

(code in playground)


Edit

Using the 2nd option I gave you, changing the delay is easy:

let theLoop: (i: number, delay?) => void = (i: number, delay = 3000) => {
    if (i % 2 === 0) {
        delay = 1500;
    }

    setTimeout(() => {
        metronome.play();
        if (--i) {
            theLoop(i);
        }
    }, delay);
};

theLoop(10);

(code in playground)




回答2:


Typescript is a upperset of Javascript. So you can copy your code into Typescript and it will work



来源:https://stackoverflow.com/questions/40919088/typescript-loop-with-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!