Delay in Updating Nativescript Slider Value

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.

Answer №1

Hooray, I've successfully tackled the issue at hand! this.interval is now set up for Two-Way-Databinding using [(ngModel)]="interval". This means I must stick with this.interval and can't switch to this.plainInterval, as it's not directly linked to the Two-Way-Databinding mechanism in place. Initially, I attempted to implement a Pipe solution, but unfortunately, it's not compatible with [(ngModel)]. So instead, I opted to tweak my existing prototype code (which was functioning well) by modifying the value of setTimeout within this.timer. Below is the revised and functional code snippet:

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); // The only alteration made: dividing by this.interval instead of hardcoding it
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

What is the best way to run a function within an if statement without duplicating code if the condition is false?

When working with relay mutation code, I find it necessary to reload the store in order for it to sync with the database. This is because if the text being added is the same as previously added text, the relay store throws an error called flattenChildren.. ...

pause in execution between iterations of a for loop

Challenge I'm currently working on a function that processes a list of strings by printing each one on a new line, with CSS animations that gradually display the string over a few seconds. However, I'm struggling to make sure that the next strin ...

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...

Localization support is working partially in a Node Express application that uses Handlebars for templating

Whenever I visit a URL with the ?lang=en query parameter, the English translation is never used. However, the Hungarian text changes work perfectly fine, displaying text to test on Hungarian in the default "hu" language without any issues. What could be ca ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

Attempting to toggle variable to true upon click, but encountering unexpected behavior

On my webpage, I have implemented a simple tab system that is only displayed when the variable disable_function is set to false. However, I am facing an issue with setting disable_function to true at the end of the page using a trigger. When this trigger ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

Typescript's Intersection Types: The Key to Overlapping Properties

Looking to create a type-safe utility function in Typescript 4.0 for comparing properties of two objects, my initial code snippet is below: export function propertiesMatch<O extends object, T extends O, S extends O>(first: T, second: S, props: (keyof ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

Javascript navigation menu failing to accurately display all pages

As I continue to enhance my website at , I have encountered an issue with the menu functionality. The menu is dynamically generated through JavaScript, scanning a folder for pages and populating them into an array. While this system functions smoothly ove ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

every cell should be painted a distinct hue

I need to create a 10x10 array in JavaScript and fill each cell in the 2D array with different colors using canvas. I have managed to do this part, but now I am stuck on how to check if each cell has a different color from its neighbors. Any suggestions ...

Having trouble obtaining the ref.current.offsetWidth?

I have been working on creating a contextMenu. My goal is to retrieve the offsetWidth and offsetHeight from ref.current, but when I console.log it, it shows as undefined. const ContextMenu: React.FC<ContextMenuProps> = props => { const thisCom ...

Extract PHP variable and incorporate it into JavaScript code

After doing some research online, I was unable to find a solution to my issue. Can anyone provide assistance with this problem? I currently have a javascript variable that contains the name of a PHP session address. I am trying to access this session valu ...

What is the best way to erase information displayed when hovering over an element using mouseout?

Whenever the user hovers over an image, an information box appears regarding that specific image. The information inside the box changes as I move over another image, but when not hovering over any images, the information box remains visible. Unfortunately ...

Is there a way to lead to a password-protected page without making it accessible through the URL?

I'm currently honing my skills in web development and embarking on a project to create an interactive puzzle website. The premise is simple - the homepage will feature just an answer input field where users can enter the correct solution to progress t ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...