Code Monkey home page Code Monkey logo

pausable_timer's Introduction

pausable_timer

CI Pub Score Latest Dart version Coverage pub package pub points popularity likes Sponsor (llucax)GitHub SponsorsLiberapayPaypalBuy Me A CoffeePatreonFlattr Sponsor (mateusfccp)GitHub Sponsors

A Dart timer that can be paused, resumed and reset.

Example using start(), pause() and reset()

import 'package:pausable_timer/pausable_timer.dart';

void main() async {
  print('Create a timer that fires in 1 second, but it is not started yet');
  final timer = PausableTimer(Duration(seconds: 1), () => print('Fired!'));
  print('So we start it');
  timer.start();

  print('And wait 1/2 second...');
  await Future<void>.delayed(timer.duration ~/ 2);
  print('Not yet fired, still 1/2 second to go!');

  print('We can pause it now');
  timer.pause();

  // When paused, time can pass but the timer won't be fired
  print('And we wait a whole second...');
  await Future<void>.delayed(timer.duration);
  print("But our timer doesn't care while it's paused");
  print('It will still wait for ${timer.duration - timer.elapsed} after '
      "it's started again");

  print('So we start it again');
  timer.start();
  print('And wait for 1/2 second again, it should have fired when we are done');
  await Future<void>.delayed(timer.duration ~/ 2);
  print('And we are done, "Fired!" should be up there ๐Ÿ‘†');
  print('Now our timer completed ${timer.tick} tick');

  print('We can reset it if we want to use it again');
  timer.reset();
  print('We have to start it again after the reset because it was not running');
  timer.start();
  print('Now we wait a whole second in one go...');
  await Future<void>.delayed(timer.duration);
  print('And we are done, so you should see "Fired!" up there again ๐Ÿ‘†');
  print('Now the timer has ${timer.tick} ticks');

  print('We can reset it and start it again');
  timer.reset();
  timer.start();

  print('And you can cancel it too, so it will not fire again');
  timer.cancel();
  print("After a timer is cancelled, it can't be used again");
  print('But important information can still be retrieved:');
  print('duration: ${timer.duration}');
  print('elapsed: ${timer.elapsed}');
  print('tick: ${timer.tick}');
  print('isPaused: ${timer.isPaused}');
  print('isActive: ${timer.isActive}');
  print('isExpired: ${timer.isExpired}');
  print('isCancelled: ${timer.isCancelled}');
}

Example pausable countdown implementation

// Example on how to implement countdown using PausableTimer.periodic
import 'dart:async';

import 'package:pausable_timer/pausable_timer.dart';

void main() async {
  // We make it "late" to be able to use the timer in the timer's callback.
  late final PausableTimer timer;
  var countDown = 5;

  print('Create a periodic timer that fires every 1 second and starts it');
  timer = PausableTimer.periodic(
    Duration(seconds: 1),
        () {
      countDown--;

      if (countDown == 0) {
        timer.pause();
      }

      print('\t$countDown');
    },
  )..start();

  print('And wait 2.1 seconds...');
  print('(0.1 extra to make sure there is no race between the timer and the '
      'waiting here)');
  await Future<void>.delayed(timer.duration * 2.1);
  print('By now 2 events should have fired: 4, 3\n');

  print('We can pause it now');
  timer.pause();

  print('And we wait for 2 more seconds...');
  await Future<void>.delayed(timer.duration * 2);
  print("But our timer doesn't care while it's paused\n");

  print('So we start it again');
  timer.start();
  print('And wait for 3.1 seconds more...');
  await Future<void>.delayed(timer.duration * 3.1);
  print('And we are done: 2, 1 and 0 should have been printed');

  print('The timer should be unpaused, inactive, expired and not cancelled');
  print('isPaused: ${timer.isPaused}');
  print('isActive: ${timer.isActive}');
  print('isExpired: ${timer.isExpired}');
  print('isCancelled: ${timer.isCancelled}');

  print('We can now reset it and start it again, now for 3 seconds');
  countDown = 3;
  timer
    ..reset()
    ..start();
  print('And wait for 3.1 seconds...');
  await Future<void>.delayed(timer.duration * 3.1);
  print('And it should be done printing: 2, 1 and 0');
}

pausable_timer's People

Contributors

github-actions[bot] avatar llucax avatar mateusfccp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

pausable_timer's Issues

`PausableTimer` should have a method to execute the passed callback

Hi @llucax,

Could we add a method to the PausableTimer class for directly firing the callback function, like _timer.fire();? This would be particularly useful when initializing a periodic timer and wanting to fire it immediately. I'm aware we can achieve this by creating a separate function and calling it before creating the timer and inside the timer, but having a built-in method would streamline the process.

Let me know, what you think. Thanks again!

Trying to make a countdown timer for video recording, but the callback is fired only once.

I tried the same with the inbuilt Timer.Periodic(), but pausing and resuming was so erratic; I had a time limit of 10 seconds, but pausing and resuming multiple times causes the total recording time to go over that limit.
I stumbled across this library from an SO answer.

When I replaced Timer.Periodic with PausableTimer, I see that it is fired only once.

Here is the sample code:

 int _start= 10;

 void startTimer() {    
    _timer = PausableTimer(
      Duration(seconds: 1),
      () {
        if (_start <= 0) {         
          recordVideo();
          setState(() {
            _isRecording = true;
          });
        } else {
          setState(() {
            _start = _start - 1;            
          });          
        }
      },
    )..start();
  }

This method will be called when the recording button is pressed.
recordVideo() is what I call to either start recording (along with startTime()) or end recording.

I know you're busy and haven't touched Dart in years, but can you help me understand what is that I'm doing wrong here and why is it being called only once?

What is meaning by "pause"?

I try to have a simple timer and need to pause it:

late final PausableTimer timer;

timer = PausableTimer(Duration(seconds: 1), () {
    print('Fired!');
    timer
        ..reset()
       ..start();
    });
    timer.start();

now I want to pause it:

timer!.pause();

But after starting again with timer!.start(); it starts from millisecond 0.
This is not good because I never hit exactly at millisecond 0 when pausing, but maybe at 323 millisecond or similar.

How can I restart the timer from the exact position where i paused it?

Pause timer periodic?

EDIT: See #45 for an example on how to implement this.

Declaring and using the timer in init state does not work like timer.periodic.

Add a periodic timer flavor

There has been already a couple of requests for an easy way to create a pausable periodic timer in #19.

People seems to expect a PausableTimer.periodic() constructor, even when it's trivial to build on top of PausableTimer bacause it trivial to reset it and start it again.

Example:

timer = PausableTimer(
    Duration(seconds: 1),
    () {
      // This is really what your callback do.
      print('A period has passed');

      // we know the callback won't be called before the constructor ends, so
      // it is safe to use !
      timer
        ..reset()
        ..start();
    },
  )..start();

Once you want your timer to go away, you can just .pause() it and that's it. There is the caveat that if the actual work your callback does takes too long, the period will stretch. If you reset the timer before doing the actual work, it can be called without any further wait if it took longer than the period. Finally the time it takes for the work to be done can be calculated and the duration of the timer adjusted accordingly, which gets much less trivial, so maybe it is a worthy addition anyway ๐Ÿค”

Callback should be called when `duration` is `Duration.zero`

The PausableTimer-Callback should be called even if the Duration is Duration.zero.
I want, that the callback is called, when timer.start() is called and the Duration is Duration.zero.

Example
var timer = PausableTimer(Duration.zero, () => debugPrint('Callback called!'));

timer.start(); // <-- 'Callback called!' should be printed

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.