Saving State

Custom functions can save data in global JavaScript variables.
In subsequent calls, your custom function may use the values saved in these variables.
Saved state is useful when users enter multiple instances of the same custom function, and they need to share data with each other.
For example, you may save the data returned from a call to a web resource to avoid making additional calls to the same web resource.


var savedTemperatures{}; 

function streamTemperature(thermometerID, caller){
     if(!savedTemperatures[thermometerID]){
         refreshTemperatures(thermometerID);
     }

     function getNextTemperature(){
         caller.setResult(savedTemperatures[thermometerID]); // setResult sends the saved temperature value to Excel.
         setTimeout(getNextTemperature, 1000); // Wait 1 second before updating Excel again.
     }
     getNextTemperature();
}

function refreshTemperature(thermometerID){
     sendWebRequestExample(thermometerID, function(data){
         savedTemperatures[thermometerID] = data.temperature;
     });
     setTimeout(function(){
         refreshTemperature(thermometerID);
     }, 1000); // Wait 1 second before reading the thermometer again, and then update the saved temperature of thermometerID.
}




© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrev