我创建了一个节拍器,使用 Nativescript Slider ( https://docs.nativescript.org/angular/code-samples/ui/slider.html ) 来设置速度(间隔)。
这段代码工作得很好(速度实时变化正确):
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);
}
但是对于上面的代码,节拍器使用 ms(毫秒)而不是 bpm(每分钟节拍数)。音乐家希望将节拍器设置为 BPM。
因此:ms = 60'000/BPM
(请参阅 => 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);
}
现在我的问题是: 当我使用 slider 时,该值无法正确更新。
即: slider 默认值为 120。好的。然后我滑动到 60。该值仍然保持在 120...然后我滑动到 200,现在值跳到 120。我可以继续滑动到 10,现在是 200。
SO:问题是,它检索旧值。当设置一个新值时,旧值就会被触发。
如何同步plainInterval
和interval
来解决问题?
最佳答案
我解决了这个问题!
this.interval
通过 [(ngModel)]="interval"
进行双向数据绑定(bind)。这意味着我无法使用 this.plainInterval
,因为它没有直接连接到 this.interval
的双向数据绑定(bind)。
我首先尝试使用管道,但 2-Way-Databinding [(ngModel)]
不允许使用管道。因此,我使用了我的原型(prototype)(但有效)代码(我在开始时提供),并且仅调整了 this.timer
中的 setTimeout 值。这是工作代码:
start(){
this.stop();
console.log("START: " + this.interval);
this.tick();
}
stop() {
clearTimeout(this.timer);
}
setInterval(interval: number) { // This function isn't required
this.interval = interval;
}
public tick() {
console.log("Tick");
this.metronome.play();
this.timer = setTimeout(this.tick.bind(this), 60000/this.interval); // This was the only change needed: 60'000 / this.interval
}
关于javascript - Nativescript slider 值延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40922803/