After developing a metronome using the Nativescript Slider here to adjust speed (interval), I encountered an issue with incorrect updating of values.
The code initially worked well, allowing real-time speed changes:
app.component.html
<Slider #sl minValue="10" maxValue="350" [(ngModel)]="interval" (valueChange)="setInterval(interval)" row="0" col="1"></Slider>
app.component.ts
public metronome = sound.create("~/pages/metronome/click.mp3");
public interval: number = 120;
public timer: number;
start(){
this.stop(); // Stop previous metronome
this.tick();
}
stop() {
clearTimeout(this.timer);
}
setInterval(interval: number) {
this.interval = interval;
}
public tick() {
console.log("Tick");
this.metronome.play();
this.timer = setTimeout(this.tick.bind(this), this.interval);
}
However, there was a problem where the metronome used milliseconds instead of beats per minute (BPM).
Hence, we needed to convert milliseconds to BPM: ms = 60'000 / BPM
(shown as this.plainInterval
)
setInterval(){
this.plainInterval = 60000 / this.interval;
}
public tick() {
console.log("Tick");
this.metronome.play();
this.timer = setTimeout(this.tick.bind(this), this.plainInterval);
}
The main issue arises when sliding the control – the value does not update correctly. For example, moving from 120 to 60 keeps showing 120, until I switch to 200, then it seemingly jumps back to 120. This inconsistency persists even when setting new values, triggering old ones unintentionally.
We need a solution that synchronizes plainInterval
and interval
to address this problem effectively.