OLD | NEW |
(Empty) | |
| 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 library async.restartable_timer; |
| 6 |
| 7 import 'dart:async'; |
| 8 |
| 9 /// A non-periodic timer that can be restarted any number of times. |
| 10 /// |
| 11 /// Once restarted (via [reset]), the timer counts down from its original |
| 12 /// duration again. |
| 13 class RestartableTimer implements Timer { |
| 14 /// The duration of the timer. |
| 15 final Duration _duration; |
| 16 |
| 17 /// The callback to call when the timer fires. |
| 18 final ZoneCallback _callback; |
| 19 |
| 20 /// The timer for the current or most recent countdown. |
| 21 /// |
| 22 /// This timer is canceled and overwritten every time this [RestartableTimer] |
| 23 /// is reset. |
| 24 Timer _timer; |
| 25 |
| 26 /// Creates a new timer. |
| 27 /// |
| 28 /// The [callback] function is invoked after the given [duration]. Unlike a |
| 29 /// normal non-periodic [Timer], [callback] may be called more than once. |
| 30 RestartableTimer(this._duration, this._callback) { |
| 31 _timer = new Timer(_duration, _callback); |
| 32 } |
| 33 |
| 34 bool get isActive => _timer.isActive; |
| 35 |
| 36 /// Restarts the timer so that it counts down from its original duration |
| 37 /// again. |
| 38 /// |
| 39 /// This restarts the timer even if it has already fired or has been canceled. |
| 40 void reset() { |
| 41 _timer.cancel(); |
| 42 _timer = new Timer(_duration, _callback); |
| 43 } |
| 44 |
| 45 void cancel() { |
| 46 _timer.cancel(); |
| 47 } |
| 48 } |
OLD | NEW |