如何在 Dart 中运行重复出现的函数? [英] How do I run a reoccurring function, in Dart?
问题描述
我想一遍又一遍地运行一个函数,中间有延迟.我怎样才能用 Dart 做到这一点?
I'd like to run a function over and over, with a delay in between. How can I do this with Dart?
推荐答案
您可以使用 Timer
类来安排一次性和重复功能.
You can use the Timer
class to schedule one-shot and repeating functions.
以下是运行重复函数的方法:
Here is how you run a repeating function:
import 'dart:async';
main() {
const oneSec = Duration(seconds:1);
Timer.periodic(oneSec, (Timer t) => print('hi!'));
}
Timer 有两个参数,一个持续时间和一个要运行的函数.持续时间必须是 Duration
的一个实例.回调必须采用单个参数,即计时器本身.
The Timer takes two arguments, a duration and a function to run. The duration must be an instance of Duration
. The callback must take a single parameter, the timer itself.
使用 timer.cancel()
取消重复计时器.这是计时器从重复计时器传递到回调运行的原因之一.
Use timer.cancel()
to cancel a repeating timer. This is one reason why timer is passed to the callback run from a repeating timer.
在延迟后安排一次性函数(执行一次,在未来的某个时间):
To schedule a one-shot function after a delay (execute once, some time in the future):
import 'dart:async';
main() {
const twentyMillis = Duration(milliseconds:20);
Timer(twentyMillis, () => print('hi!'));
}
请注意,一次性定时器的回调不带参数.
Notice the callback for a one-shot timer does not take a parameter.
你也可以要求尽快运行一个函数,至少在未来一个事件循环周期.
You can also request that a function is run as soon as possible, at least one event-loop tick in the future.
import 'dart:async';
main() {
Timer.run(() => print('hi!'));
}
在 HTML 中
定时器甚至可以在 HTML 中工作.事实上,window.setTimeout
被移除了,所以 Timer 是未来运行函数的唯一途径.
In HTML
Timers even work in HTML. In fact, window.setTimeout
was removed, so Timer is the only way to run a function in the future.
这篇关于如何在 Dart 中运行重复出现的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!