gpt4 book ai didi

javascript - 带延迟的 typescript 循环

转载 作者:行者123 更新时间:2023-12-02 13:52:45 25 4
gpt4 key购买 nike

我正在尝试使用 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);

有人可以帮我解决这个问题吗?

最佳答案

正如大家所说,typescipt 是 javascript 的超集,因此您的代码是有效的 typescript,但以下是如何使用箭头函数(也是 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 )

关于javascript - 带延迟的 typescript 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40919088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com