0

I'm new to programming and flutter and I just got stuck with this.

I want to build a metronome that can accelerate at fixed intervals. For example, every 5 seconds the timer gets faster by 10 beats per minute.

I coded the basic metronome using Timer.periodic; now, I thought that using a new Timer.periodic to accelerate the previous timer every 5 seconds could work, and actually I don't know if it does.

If I cancel the previous instance of the timer, modify the duration, and start a new timer, I can hear the gap and then it's asynchronous. Is there an easier way to modify it while it's still running? Or is there some other way?

GRC
  • 111
  • 1
  • 1
  • 6

1 Answers1

0

There isn't a way to modify the interval of a Timer when it's running, so the only way would be to fire a new one with the modified interval like you are doing.

However, might I suggest an alternative solution where instead of canceling the previous timer, you wait for it to complete before firing a new one. This would eliminate the "gap" that forms. (Interestingly enough, this might be a bit annoying to manage with a Timer.periodic, so you could try using a plain Timer.)

class Metronome {
  double tempo;
  bool active = false;

  Metronome([this.tempo = 60.0]);

  void start() {
    active = true;
    Timer(_getDuration(), _handleEvent);
  }

  void stop() {
    active = false;
  }

  void _handleEvent() {
    // TODO: Handle metronome event, e.g. make the tick sound

    if (active) {
      Timer(_getDuration(), _handleEvent);
    }
  }

  Duration _getDuration() {
    final time = 1 / tempo;
    return Duration(
      seconds: time.toInt(),
      milliseconds: (time * 1000).toInt() % 1000,
      microSeconds: (time * 1000000).toInt() % 1000,
    );
  }
}
Abion47
  • 22,211
  • 4
  • 65
  • 88
  • Thank you, I didn't know you could use Timer to do repeating actions. Now I have to sort a way to accelerate it. – GRC Feb 09 '20 at 14:30