打字节拍器 [英] Typescript Metronome

查看:98
本文介绍了打字节拍器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Typescript(和Angular 2)构建一个节拍器。
感谢@ Nitzan-Tomer(带延迟的Typescript循环),

I'm trying to build a metronome with Typescript (and Angular 2). Thanks, to @Nitzan-Tomer (Typescript Loop with Delay), who helped me with the basics.

现在我面临的问题是,在启动节拍器后,我无法更改间隔。想象一个滑块,改变声音之间的速度(=>间隔)。

Now I'm facing the issue, that after I started the metronome, I'm not able to change the interval. Imagine a slider, changing the speed between the sounds (=> interval).

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

theLoop(10);

这里的间隔是3000。我希望能够在触发函数后对其进行更改。 (也许也可以摆脱 i:number ?因为它不应该只播放节拍器声音10次...

The interval here is 3000. And I want to be able to change it, after the function was triggered. (Maybe also get rid of the i: number? Because it shouldn't just play the metronome-sound 10 times...

我想到了一个类?但是我不确定如何构建它...

I thought of a class? But I'm not sure how to build it...

推荐答案

一个简单的类就可以做到:

Here's a simple class to do it:

class Metronome {
    private interval: number;
    private timer: number;

    constructor(interval = 3000) {
        this.interval = interval;
    }

    start(): void {
        this.tick();
    }

    stop() {
        clearTimeout(this.timer);
    }

    setInterval(interval: number) {
        this.interval = interval;
    }

    private tick() {
        // do something here
        this.timer = setTimeout(this.tick.bind(this), this.interval);
    }
}

操场上的代码

这篇关于打字节拍器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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