Search code examples
javascriptsetintervalcountdownnativescript

Nativescript getViewById not updating for count down


So, i am using the timer that i asked about in this question as a count down: How to stop timer.setinterval with a tap event or leaving page in nativescript

The counter works, all this while i have been using console.log to check if it works and yes it does but i want to make it appear in the xml for the user of that app to see. But the count does not update in the xml.

Here's the code for the view:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded" navigatedTo="navigatedTo" navigatingFrom="onNavigatingFrom" actionBarHidden="true">

    <DockLayout orientation="horizontal" horizontalAlignment="center" backgroundColor="black" color="white">
        <Label text="Time remaining: " dock="left" margin="5" />
        <Label id="timeCount" text="" loaded="pageLoaded"></Label>
    </DockLayout>    
</Page>

And the js file behind:

var time;
var timeKeep = vm.time;
var count = 0;

function timeCountDown () {
    time = vm.time--;                    //this is the value that i need
    console.log("i is " + time);
}  

countId = timer.setInterval(() => {
    timeCountDown();
    count += 1;
    if (count === timeKeep) {
        timer.clearInterval(countId);
        dialogs.alert({
            title: "Time Up!",
            message: "You did not finish the test in time.",
            okButtonText: "OK"
        });
        aemnavigation.goResults(vm.correct);
    }
}, 1000);  



//the two lines below is how i get it to show on the xml

TimeCountScore = page.getViewById("timeCount");
TimeCountScore.text = time;

The value of time gets to the view but it's not updated has the value counts down. I console.log(time) to make sure that it still counts.


Solution

  • You should you data binding that inherits the Observable class, when a property is changed it will update the XML also. For your case, if you still want to keep your practice you can put the label.text inside the interval to get it updated:

    TimeCountScore = page.getViewById("timeCount");
    
    countId = timer.setInterval(() => {
        TimeCountScore.text = time;
    }, 1000);