带延迟的打字稿循环

时间:2016-12-01 19:42:09

标签: javascript loops typescript delay

我正在尝试用Typescript创建一个节拍器。

我有这个javascript代码:

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

我想将其转换为Typescript代码。不幸的是我不知道该怎么做(特别关于最后一行=> })(10);

有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:1)

TypescriptJavascript的粉丝。因此,您可以将代码复制到Typescript并且可以正常使用

答案 1 :(得分:1)

正如大家所说,typescipt是​​javascript的超集,所以你的代码是有效的打字稿,但是这里是如何使用箭头函数(也是es6 javascript)和类型:

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

code in playground

这是另一种变化:

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

theLoop(10);

code in playground

修改

使用我给你的第二个选项,更改延迟很容易:

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

相关问题