Running a recurring function

Let's suppose your code needs to run a certain function periodically at a certain interval. This recipe shows how you can do this very easily.

How to do it...

Look at the following code of recurring_function.dart:

import'dart:async';

var count = 0;
const TIMEOUT = const Duration(seconds: 5);
const MS = const Duration(milliseconds: 1);

void main() {
  // 1. Running a function repeatedly:
  const PERIOD = const Duration(seconds:2);
  newTimer.periodic(PERIOD, repeatMe);
  // 3. Running a function once after some time:
  const AFTER70MS = const Duration(milliseconds:70);
  new Timer(AFTER70MS, () => print('this was quick!'));
  // 4. Running a function asap:
  Timer.run(() => print('I ran asap!'));
  // 5. Calculating a period and provoking a timeout:
  startTimeout(500);
}

repeatMe(Timer t) {
  print("I have a repetetive job, and I'm active is ${t.isActive}!");
  count++;
  // 2. Stop the repetition:
  if (count==4 &&t.isActive) {
  t.cancel();
  print("I'm active is ${t.isActive} now");
  }
}

startTimeout([intvariableMS ]) {
  var duration = variableMS  == null ? TIMEOUT : MS * variableMS;
  return new Timer(duration, handleTimeout);
}

handleTimeout() {
  print('I was timed out!'),
}

The following is the output from this code; if you need help figuring out the order, read the next section:

I ran asap!

this was quick!

I was timed out!

I have a repetetive job, and I'm active is true!

I have a repetetive job, and I'm active is true!

I have a repetetive job, and I'm active is true!

I have a repetetive job, and I'm active is true!

I'm active is false now

How it works...

The Timer class from dart:async gives us this functionality through the periodic named constructor as shown in comment 1. This takes two arguments, a Duration object and a function (here repeatMe) to run, which has the timer as the single parameter. This comes in handy to stop the repetition, which is shown in comment 2 with the cancel() method after 4 repetitions. The isActive property can be used to test whether the repetition is still going on. Comment 3 shows how to run a function only once after a time interval; just use the normal Timer constructor with the same arguments, but the callback doesn't have a Timer parameter. To run a function as soon as the event-loop mechanism permits, use the static run method as shown in comment 4. A negative or zero duration is equivalent to calling run. Comment 5 shows that a Timer class can also be useful to stop a running function or even the entire app.

There's more...

The durations or periods don't have to be constant from the start; they can be calculated before starting the Timer. Timers can also be used in web applications, but for drawing purposes, use window.animationFrame. When your app is compiled to JavaScript, the finest time granularity that the browser can give you is 4 milliseconds.

See also

  • Refer to the Writing a game-loop recipe in this chapter for more information on window.animationFrame
  • Refer to the Exiting from an app recipe in Chapter 2, Structuring, Testing, and Deploying an Application, for other alternatives to stop a running app
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset