Реализация интервальных таймеров в Dart: примеры и код

Таймер интервального таймера dart относится к реализации интервального таймера в языке программирования Dart. Ниже приведены несколько способов добиться этого с примерами кода:

Метод 1: использование функции Timer. periodic

import 'dart:async';
void main() {
  Timer.periodic(Duration(seconds: 1), (Timer timer) {
    // Code to be executed repeatedly after every second
    print('Interval timer example');
  });
}

Метод 2. Использование рекурсивной функции с Future.delayed

import 'dart:async';
void intervalTimer() {
  // Code to be executed repeatedly
  print('Interval timer example');
  // Recursive call after a delay of 1 second
  Future.delayed(Duration(seconds: 1), intervalTimer);
}
void main() {
  // Start the interval timer
  intervalTimer();
}

Метод 3. Использование асинхронной функции с await Future.delayed

import 'dart:async';
void main() async {
  while (true) {
    // Code to be executed repeatedly
    print('Interval timer example');
    // Delay for 1 second
    await Future.delayed(Duration(seconds: 1));
  }
}

Метод 4. Использование специального класса для интервального таймера

import 'dart:async';
class IntervalTimer {
  Timer _timer;
  Duration _interval;
  Function _callback;
  IntervalTimer(this._interval, this._callback);
  void start() {
    _timer = Timer.periodic(_interval, (_) => _callback());
  }
  void stop() {
    _timer?.cancel();
  }
}
void main() {
  final interval = Duration(seconds: 1);
  final timer = IntervalTimer(interval, () {
    // Code to be executed repeatedly
    print('Interval timer example');
  });
  timer.start(); // Start the interval timer
  // Stop the interval timer after 5 seconds
  Timer(Duration(seconds: 5), timer.stop);
}