Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dart 的 Timer #83

Open
huruji opened this issue Sep 21, 2019 · 0 comments
Open

Dart 的 Timer #83

huruji opened this issue Sep 21, 2019 · 0 comments

Comments

@huruji
Copy link
Owner

huruji commented Sep 21, 2019

Timer 属于 Dart 异步编程的一部分,通过 Timer 可以创建执行定时器(包括重复执行的)。

主要包含 TimerTimer.periodic 两个构造函数:

Timer(Duration duration, void callback())
Timer.periodic(Duration duration, void callback(Timer timer))

分别对应 javascript 的 setTimeoutsetInterval

如 3 秒之后打印:

  const timeout = Duration(seconds: 3);

  Timer(timeout, () {
    print('huruji');
  });

1 秒重复打印:

Timer.periodic(Duration(seconds: 1), (Timer timer) {
    print('xie');
  });

需要取消定时器,可以使用实例方法 .cancel

  int count = 0;

  Timer myTimer;
  myTimer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
    print('xie');
    if (count == 10) {
      myTimer.cancel();
    }
    count++;
  });

Dart 和 js 一样都是单线程,所以为了能够让定时器尽快的调用,可以使用静态方法 run

Timer.run(callback)

这类似于将 setTimeout 的时间设置为 0

setTimeout(() => {}, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant