Wait and Repeat

Wait

When you want to pause a device like for waiting a response from a sensor use wait(). It pause both device and program.

// Javascript Example

led.on();
await obniz.wait(1000); // led ON for 1sec.
led.off();

Remove await to keep working program side.

// Javascript Example

var time = new Date();
led.on();
obniz.wait(1000); // led ON 1sec.
led.off();
console.log((new Date()).getTime() - time.getTime()) // 0 or very few ms. not 1000ms.

Or To stop only javascript then

// Javascript Example

var time = new Date();
led.on();
await new Promise((resolve) => { setTimeout(resolve, 1000) });
led.off();

Repeat

To repeatedly call a function while the device is connected, obniz.onloop is useful.
A function set here will be called repeatedly as long as the device is online.

// Javascript Full Example

var obniz = new Obniz("OBNIZ_ID_HERE");
obniz.onconnect = async function () {
  obniz.onloop = async function () {
    // called while online
  }
}

This function calls pingWait() internally every time to check for communication and to ensure that the communication channel does not accumulate a large number of buffers. Therefore, if you want to iterate faster, you can do so by looping or iterating in your program instead of using onloop, but there are some caveats

  • When disconnected from a device, break a loop.
  • avoid freeze.

Most safety loop is below.

// Javascript Example

while(obniz.connectionState === 'connected') {
  try {
    // something code
    await obniz.pingWait(); // check communication
  } catch(e) {
    // break or throw a error
  }
}

connectionState represents connection status for a device.
pingWait() send a data and wait for a response.
Above code will break a loop if offline and avoiding a freeze and also clean up communication line by using ping.

関連の質問