带延迟的Typescript循环 [英] Typescript Loop with Delay

查看:433
本文介绍了带延迟的Typescript循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a metronome with Typescript.

我有以下javascript代码:

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

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

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

有人可以帮我吗?

推荐答案

大家都说,typecipt是​​javascript的超集,因此您的代码是有效的typescript ,但这是使用箭头功能(也是 es6 javascript)和类型的方法:

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);

操场上的代码

这是另一个变体:

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

theLoop(10);

操场上的代码

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

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);

操场上的代码

这篇关于带延迟的Typescript循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆