如何在Dart SDK 0.4+中使用setInterval/setTimeout

mar*_*tin 17 dart dart-html

我意识到,在当前飞镖SDK版本0.4.1.0_r19425方法,如setTimeout,setInterval,clearTimeout,clearInterval是不是部分Window类更多,他们都搬到了WorkerContext.
现在有没有关于如何使用它们的文档?WorkerContext每次我想使用它们时是否需要创建一个新实例?

Sea*_*gan 34

除了Chris提到的Timer之外,还有一个基于Future的 API:

var future = new Future.delayed(const Duration(milliseconds: 10), doStuffCallback);
Run Code Online (Sandbox Code Playgroud)

取消Future回调还没有直接的支持,但是效果很好:

var future = new Future.delayed(const Duration(milliseconds: 10));
var subscription = future.asStream().listen(doStuffCallback);
// ...
subscription.cancel();
Run Code Online (Sandbox Code Playgroud)

希望很快就会有一个Stream版本的Timer.repeating.


Chr*_*ett 10

来自该组的帖子(2013年2月14日).

// Old Version
window.setTimeout(() { doStuff(); }, 0);

// New Version
import 'dart:async';
Timer.run(doStuffCallback);
Run Code Online (Sandbox Code Playgroud)

另一个例子(从同一篇文章复制)

// Old version: 
var id = window.setTimeout(doStuffCallback, 10);
.... some time later....
window.clearTimeout(id);

id = window.setInterval(doStuffCallback, 1000);
window.clearInterval(id);

// New version:
var timer = new Timer(const Duration(milliseconds: 10), doStuffCallback);
... some time later ---
timer.cancel();

timer = new Timer.repeating(const Duration(seconds: 1), doStuffCallback);
timer.cancel();
Run Code Online (Sandbox Code Playgroud)

具体来说,它们现在Timerdart:async库中类的一部分(而不是WorkerContext,它似乎是IndexedDb特定的). API文档在这里

  • 我提醒不要使用计时器,除非你把try/catch放在Timer里面.如果在Timer内部抛出异常,并且你没有捕获它,游戏结束和app over.您可能希望使用Future.delayed,它不仅可以正确捕获异常,还可以让您知道它何时实际完成.期货组合也更好. (3认同)

小智 9

您可以使用:

1) 设置间隔

_timer = new Timer.periodic(const Duration(seconds: 2), functionBack);

Where: `functionBack(Timer timer) {
  print('again');
}
Run Code Online (Sandbox Code Playgroud)

2) 设置超时

_timer = Timer(Duration(seconds: 5), () => print('done'));

Where _time is type Time
Run Code Online (Sandbox Code Playgroud)