PRE-REQUISITES

For the following code examples to work, you will need to add Fliplet’s Data Sources API to your app. To add it follow the steps referenced here.

You may wish to run some custom code after a certain time has elapsed. For example you may want to close an exam after the exam time is up or routinely check if new data is available on the datasource.

To create code that is only run once you can use a setTimeout function. You should note that if the app is closed before the time is up then this code will not be run. Similarly, if this code is located in a specific screen rather than within the “Global” tab of the Developer Options, if the user changes screen before the timeout is up then this function will not be run.

The example below waits for 10,000 milliseconds (ie, 10 seconds) to pass before running.

setTimeout(function () {
   // Add the code you want to run here.
   // It will run after 10,000 milliseconds ie, 10 seconds
}, 10000);

Alternatively, we can repeatedly run an action after a certain time interval has passed. The code below creates an interval that will run every 10 seconds. If a user closes the app or if the code is specific to a screen (ie, not global) and the user navigates to another screen – then the code may not be run.

function doSomething() {
  // Do something

  // Run the function again in 10 seconds
  setTimeout(function () {
    doSomething();
  }, 10000);
}

doSomething();

We’re provided a more detailed example below where we connect to a data source every 10 seconds to see if new updates are available. Every 10 seconds we run a function getDataSourceRecords which looks for the data source with the ID provided (123456). The code then saves the data source data to dataSourceRecords (these are the rows of data in your data source). If there is an error eg, a data connection can’t be made or times out, we will retry to get the data.

var period = 10000; // 10 seconds
var dataSourceId = 123456;
var dataSourceRecords;

function getDataSourceRecords(id) {
  return Fliplet.DataSources.connect(id)
    .then(function (connection) {
      return connection.find();
    })
    .then(function (results) {
      dataSourceRecords = results;

      // Run the function again in 10 seconds
      setTimeout(function () {
        getDataSourceRecords(id);
      }, period);
    }).catch(function (error) {
      // Handle the error

      // Make sure the loop doesn't stop on error
      // Run the function again in 10 seconds
      setTimeout(function () {
        getDataSourceRecords(id);
      }, period);    
    });;
}

getDataSourceRecords(dataSourceId);