Having a datafield value update every few seconds?

I have a datafield value that updates every second (calories per hr). I'd like this to only update every 3 or 5 seconds.

How do I get a compute function to only update every few seconds instead of every second?

Thanks
  • You can skip some ticks, using counter.

    class DataField extends Ui.SimpleDataField
    {
    var value_picked = "---";
    var counter = 0;
    ...
    function compute(info)
    {
    if( counter == 3 )
    {
    if( info.currentHeartRate != null )
    {
    value_picked = info.currentHeartRate;
    }
    else value_picked = "---";
    }
    counter += 1;
    if( counter > 3 )
    {
    counter = 0;
    }

    return value_picked;
    }
    ...
    }
  • The way DF's work, is that when they are visible, the screen is cleared before the DF is called, so to have a value that doesn't "flash" (only has something in it every few seconds), is you always want to display a value in onUpdate() (for a complex data field) or return in compute() (simple DF)

    There are a couple things you can use:
    onUpdate() is called every second, but only when a DF is visible (if you're on a different screen onUpdate() isn't called)
    compute() is called every second, even if the DF isn't visible.

    With this, you should be doing your computations in compute() and not onUpdate() if they are time dependant.

    So if you want the value to not "bounce around" every second, what you can do is in compute(), keep calculating it as you do now, but only change what you'll be displaying every 3rd,4th, etc time that compute() is called. (a variable for your current computation, and a second one for what you want displayed.

    so something like this:

    var counter=0;
    var data=null;
    var displayData=null;

    function compute(info) {
    //do whatever you do to calculate "data"

    if(counter%3==0 || displayData==null) {
    //copy "data" to "displayData" - it happens every 3 seconds with the "%3"
    }
    counter++;

    //return "displayData" here for a simple DF or in onUpdate(), use "displayData" and not "data"
    }


    (there are things you'll want to do like null checks for things in info, etc, but this is the basic logic - warning! untested code and there might be a typo to three!)
  • Thanks all for the replies. I was able to learn from your examples and get things working as planned!