41

I'm porting some JavaScript to Dart. I have code that uses window.setTimeout to run a callback after a period of time. In some situations, that callback gets canceled via window.clearTimeout.

What is the equivalent of this in Dart? I can use new Future.delayed to replace setTimeout, but I can't see a way to cancel this. Nor can I find away to call clearTimeout from Dart.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275

2 Answers2

82

You can use the Timer class

import 'dart:async';

var timer = Timer(Duration(seconds: 1), () => print('done'));

timer.cancel();
JChen___
  • 3,593
  • 2
  • 20
  • 12
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Cool; will try this. Is `Timer` just a wrapper around a `Future` that's internally setting a `bool` when canceled? – Danny Tuppeny Nov 21 '14 at 14:17
  • 2
    As far as I know this is not how it is. `Future.delayed` uses a `Timer` but otherwise I think they are not related (not sure though). – Günter Zöchbauer Nov 21 '14 at 14:18
  • 2
    Yes use Time for something that can be cancelled. Future.delayed uses a Timer in the background, not vice versa. You can see the implementation here: https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/sdk/lib/async/future.dart#224 – Matt B Nov 21 '14 at 14:21
  • The Dart source code is now available on GitHub. The link to the `Future.delayed` factory is available here: https://github.com/dart-lang/sdk/blob/master/sdk/lib/async/future.dart – Vince Varga Jul 10 '19 at 10:57
2

If you want to mimic the JavaScript API:

import 'dart:async';

Timer setTimeout(callback, [int duration = 1000]) {
  return Timer(Duration(milliseconds: duration), callback);
}

void clearTimeout(Timer t) {
  t.cancel();
}
Krasimir
  • 13,306
  • 3
  • 40
  • 55