如何在Dart中运行重复功能?

How do I run a reoccurring function, in Dart?

我想一遍又一遍地运行一个函数,之间要有一个延迟。 如何使用Dart做到这一点?


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

重覆

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

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

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

取消重复计时器

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

延迟一拍

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

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

请注意,单次计时器的回调没有参数。

尽快一拍

您还可以要求尽快运行一个功能,至少在将来至少一个事件循环中运行一次。

1
2
3
4
import 'dart:async';
main() {
  Timer.run(() => print('hi!'));
}

在HTML中

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


https://api.dartlang.org/stable/1.24.3/dart-async/Stream/Stream.periodic.html

1
2
3
4
5
6
7
8
9
import 'dart:async';

StreamSubscription periodicSub;

void main() {
  periodicSub = new Stream.periodic(const Duration(milliseconds: 500), (v) => v)
      .take(10)
      .listen((count) => print('tick $count'));
}

或者如果不需要计数器

1
2
3
4
5
6
7
8
9
import 'dart:async';

StreamSubscription periodicSub;

void main() {
  periodicSub = new Stream.periodic(const Duration(milliseconds: 500))
      .take(10)
      .listen((_) => print('tick'));
}


5秒计时器示例

1
2
3
4
5
6
7
8
9
10
bool isStopped = false; //global

sec5Timer() {
  Timer.periodic(Duration(seconds: 5), (timer) {
    if (isStopped) {
      timer.cancel();
    }
    print("Dekhi 5 sec por por kisu hy ni :/");
  });
}

从任何功能调用

1
sec5Timer();

停止任何功能

1
isStopped = true;

要处置,您可以使用此代码或技术。

1
2
3
4
5
6
7
8
9
10
11
12
 @override
  void initState() {
    _timer = new Timer.periodic(widget.refreshRate,
      (Timer timer) => _updateDisplayTime(inheritedWidget));
    super.initState();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }


您还可以使用Future.delayed并等待延迟执行:

1
2
3
4
5
6
7
8
9
Future<Null> delay(int milliseconds) {
  return new Future.delayed(new Duration(milliseconds: milliseconds));
}


main() async {
  await delay(500);
  print('Delayed 500 milliseconds');
}


替代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import 'dart:async';

Timer interval(Duration duration, func) {
  Timer function() {
    Timer timer = new Timer(duration, function);

    func(timer);

    return timer;
  }

  return new Timer(duration, function);
}

void main() {
  int i = 0;

  interval(new Duration(seconds: 1), (timer) {
    print(i++);

    if (i > 5) timer.cancel();
  });
}


在功能上与JavaScript相同的代码(setInterval,setTimeout,clearInterval和clearTimeout):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// ------------------------------
// Import:

import 'dart:async';

// ------------------------------
// Definitions:

void clearTimeout(Timer timer) {
  try {
    timer.cancel();
  } catch (e) {}
}

Timer setTimeout(VoidCallback fn, int millis) {
  Timer timer;
  if (millis > 0)
    timer = new Timer(new Duration(milliseconds: millis), fn);
  else
    fn();
  return timer;
}

void clearInterval(Timer timer) {
  try {
    timer.cancel();
  } catch (e) {}
}

Timer setInterval(VoidCallback fn, int millis) {
  Timer timer;
  if (millis > 0)
    timer = new Timer.periodic(new Duration(milliseconds: millis), (timer) {
      fn();
    });
  else
    fn(); // If millis input is too low, only run function once and stop
  return timer;
}

// ---------------------------------
// Example:

int myValue = 0;

Timer counter = setInterval((){ myValue++; }, 50);
setTimeout((){
    clearInterval(counter);
}, 5000);