Line data Source code
1 : // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
2 : // for details. All rights reserved. Use of this source code is governed by a
3 : // BSD-style license that can be found in the LICENSE file.
4 :
5 : import 'dart:async';
6 :
7 : /// A non-periodic timer that can be restarted any number of times.
8 : ///
9 : /// Once restarted (via [reset]), the timer counts down from its original
10 : /// duration again.
11 : class RestartableTimer implements Timer {
12 : /// The duration of the timer.
13 : final Duration _duration;
14 :
15 : /// The callback to call when the timer fires.
16 : final ZoneCallback _callback;
17 :
18 : /// The timer for the current or most recent countdown.
19 : ///
20 : /// This timer is canceled and overwritten every time this [RestartableTimer]
21 : /// is reset.
22 : Timer _timer;
23 :
24 : /// Creates a new timer.
25 : ///
26 : /// The [callback] function is invoked after the given [duration]. Unlike a
27 : /// normal non-periodic [Timer], [callback] may be called more than once.
28 0 : RestartableTimer(this._duration, this._callback) {
29 0 : _timer = new Timer(_duration, _callback);
30 : }
31 :
32 0 : bool get isActive => _timer.isActive;
33 :
34 : /// Restarts the timer so that it counts down from its original duration
35 : /// again.
36 : ///
37 : /// This restarts the timer even if it has already fired or has been canceled.
38 : void reset() {
39 0 : _timer.cancel();
40 0 : _timer = new Timer(_duration, _callback);
41 : }
42 :
43 : void cancel() {
44 0 : _timer.cancel();
45 : }
46 : }
|