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?
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?
Share Improve this question asked Dec 1, 2016 at 19:42 TaremehTaremeh 3222 gold badges4 silver badges13 bronze badges 4-
TypeScript is just a superset of JavaScript. On the other hand, the metronome should probably have a way of changing it's tempo and a way of starting it and stopping it as well as making it tick on demand. Basically I'd expect
metronome.changeTempo(bpm); metronome.onTick(function () { if (...) metronome.stop(); }); metronome.play();
. You could also have a built-in feature specific to ticking a number of times.metronome.tick(10)
. – plalx Commented Dec 1, 2016 at 19:56 - @plalx I like your idea! What would the code look like? Or: How can I approach it? – Taremeh Commented Dec 1, 2016 at 20:18
-
Do you know a bit of OO? Look at the
class
keyword and examples on how to use it. Metronome would be a class here, not an Audio file. It could take an audio as a constructor parameter though..let metronome = new Metronome(new Audio('tick.mp3'))
. – plalx Commented Dec 1, 2016 at 20:24 - @plalx Do you know a tutorial regarding this topic? Because I'm unfortunately not this far in OO... – Taremeh Commented Dec 1, 2016 at 20:57
2 Answers
Reset to default 3As 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)
Typescript
is a upperset of Javascript
. So you can copy your code into Typescript
and it will work
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744234263a4564398.html
评论列表(0条)