2013-03-08 86 views

回答

15

除了由克里斯提到的定时器,有一个Future-based API:

var future = new Future.delayed(const Duration(milliseconds: 10), doStuffCallback); 

没有取消的Future回调尚未直接支持,但这个工作得很好:

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

希望很快会出现Stream version of Timer.repeating

+0

所以如果我理解正确的话,使用Future是推荐的方法。 – martin 2013-03-10 20:41:51

7

从此post on the group(2013年2月14日)。

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

// New Version 
import 'dart:async'; 
Timer.run(doStuffCallback); 

而另一示例(从相同的交复制)

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

具体地,它们是目前在dart:async库(而不是WorkerContext,这似乎是索引资料特定的)的Timer类的一部分。 API docs here

+3

我谨慎使用计时器,除非你把计时器内的try/catch。如果在Timer内部抛出异常,并且您没有捕获它,则游戏结束并结束应用。您可能想要使用Future.delayed,它不仅正确捕获异常,而且还提供了一个知道何时实际完成的句柄。期货构成也更好。 – 2013-03-10 16:13:35