How do I do the equivalent of setTimeout + clearTimeout in Dart?

29.1k Views Asked by At

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.

2

There are 2 best solutions below

4
On BEST ANSWER

You can use the Timer class

import 'dart:async';

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

timer.cancel();
0
On

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();
}