Typescript Metronome

吃可爱长大的小学妹 提交于 2019-12-12 02:43:08

问题


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

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...


回答1:


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

(code in playground)



来源:https://stackoverflow.com/questions/40920820/typescript-metronome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!