Timer class

A count-down timer that can be configured to fire once or repeatedly.

The timer counts down from the specified duration to 0. When the timer reaches 0, the timer invokes the specified callback function. Use a periodic timer to repeatedly count down the same interval.

A negative duration is treated the same as a duration of 0. If the duration is statically known to be 0, consider using run.

Frequently the duration is either a constant or computed as in the following example (taking advantage of the multiplication operator of the Duration class):

const timeout = Duration(seconds: 3);
const ms = Duration(milliseconds: 1);

Timer startTimeout([int? milliseconds]) {
  var duration = milliseconds == null ? timeout : ms * milliseconds;
  return Timer(duration, handleTimeout);
}
...
void handleTimeout() {  // callback function
  ...
}

Note: If Dart code using Timer is compiled to JavaScript, the finest granularity available in the browser is 4 milliseconds.

See Stopwatch for measuring elapsed time.

Constructors

Timer(Duration duration, void callback())
factory
Creates a new timer. [...]
Timer.periodic(Duration duration, void callback(Timer timer))
factory
Creates a new repeating timer. [...]

Properties

hashCodeint
read-only, inherited
The hash code for this object. [...]
isActivebool
read-only
Returns whether the timer is still active. [...]
runtimeTypeType
read-only, inherited
A representation of the runtime type of the object.
tickint
read-only
The number of durations preceding the most recent timer event. [...]

Methods

cancel() → void
Cancels the timer. [...]
noSuchMethod(Invocation invocation) → dynamic
inherited
Invoked when a non-existent method or property is accessed. [...]
toString() → String
inherited
A string representation of this object. [...]

Operators

operator ==(Object other) → bool
inherited
The equality operator. [...]

Static Methods

run(void callback()) → void
Runs the given callback asynchronously as soon as possible. [...]

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dart.dev/stable/2.13.0/dart-async/Timer-class.html