如何在Dart中运行重复功能? [英] How do I run a reoccurring function, in Dart?

查看:84
本文介绍了如何在Dart中运行重复功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一遍又一遍地运行一个函数,但要间隔一段时间。如何使用Dart做到这一点?

解决方案

您可以使用 Timer 类来安排单发和重复功能。



重复



这是运行重复功能的方式:

  import'dart:async'; 
main(){
const oneSec = const Duration(seconds:1);
new Timer.periodic(oneSec,(Timer t)=> print(’hi!’));
}

Timer需要两个参数,一个持续时间和一个要运行的函数。持续时间必须是 Duration 的实例。回调必须使用单个参数,即计时器本身。



取消重复计时器



使用 timer.cancel()取消重复计时器。这是计时器将计时器从重复计时器传递到回调运行的原因之一。



延迟后一次拍摄



要在延迟后安排一次功能(执行一次,以后再执行一次):

  import'dart:async'; 
main(){
const 20.Millis = const持续时间(毫秒:20);
new Timer(twentyMillis,()=> print(’hi!’));
}

请注意,单次计时器的回调不带参数。 / p>

尽快拍摄



您还可以要求尽快运行某个函数,

  import'dart:async'; 
main(){
Timer.run(()=> print(’hi!’));
}



在HTML中



计时器甚至可以HTML格式工作。实际上, window.setTimeout 已被删除,因此Timer是将来运行函数的唯一方法。


I'd like to run a function over and over, with a delay in between. How can I do this with Dart?

解决方案

You can use the Timer class to schedule one-shot and repeating functions.

Repeating

Here is how you run a repeating function:

import 'dart:async';
main() {
  const oneSec = const Duration(seconds:1);
  new Timer.periodic(oneSec, (Timer t) => print('hi!'));
}

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.

Canceling a repeating timer

Use timer.cancel() to cancel a repeating timer. This is one reason why timer is passed to the callback run from a repeating timer.

One-shot after a delay

To schedule a one-shot function after a delay (execute once, some time in the future):

import 'dart:async';
main() {
  const twentyMillis = const Duration(milliseconds:20);
  new Timer(twentyMillis, () => print('hi!'));
}

Notice the callback for a one-shot timer does not take a parameter.

One-shot as soon as possible

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!'));
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆