Giter Site home page Giter Site logo

use-timer's Introduction

⏱️ use-timer

npm Version License Linux Build Status Bundle size Bundle size

Simple timer turned into React Hooks. Read about Hooks feature.

Installation

npm i use-timer

With Yarn:

yarn add use-timer

Demo

Netlify Status

🚀 Try last production version on Netlify!

https://use-timer.netlify.app/

Usage

Basic timer

import React from 'react';
import { useTimer } from 'use-timer';

const App = () => {
  const { time, start, pause, reset, status } = useTimer();

  return (
    <>
      <div>
        <button onClick={start}>Start</button>
        <button onClick={pause}>Pause</button>
        <button onClick={reset}>Reset</button>
      </div>
      <p>Elapsed time: {time}</p>
      {status === 'RUNNING' && <p>Running...</p>}
    </>
  );
};

Decremental timer

const { time, start, pause, reset, status } = useTimer({
  initialTime: 100,
  timerType: 'DECREMENTAL',
});

Timer with end time

const { time, start, pause, reset, status } = useTimer({
  endTime: 30,
  initialTime: 10,
});

Advance time

This works for all types of timer (incremental and decremental).

const { time, start, advanceTime } = useTimer({
  initialTime: 20,
});

start();
advanceTime(10);

console.log(time); // 30

Callbacks

Some callback functions can be provided.

When time is over

const { time, start, pause, reset, status } = useTimer({
  endTime,
  onTimeOver: () => {
    console.log('Time is over');
  },
});

When time is updated

const { time, start, pause, reset, status } = useTimer({
  endTime,
  onTimeUpdate: (time) => {
    console.log('Time is updated', time);
  },
});

Configuration

The configuration and all its parameters are optional.

Property Type Default value Description
autostart boolean false Pass true to start timer automatically
endTime number null The value for which timer stops
initialStatus string "STOPPED" The initial status for the timer. Options are: "RUNNING", "PAUSED", and "STOPPED"
initialTime number 0 The starting value for the timer
interval number 1000 The interval in milliseconds
onTimeOver function Callback function that is called when time is over
onTimeUpdate function Callback function that is called when time is updated
step number 1 The value to add to each increment / decrement
timerType string "INCREMENTAL" The choice between a value that increases ("INCREMENTAL") or decreases ("DECREMENTAL")

use-timer's People

Contributors

aksjer avatar dependabot[bot] avatar ervinebalo avatar luispuig avatar renovate[bot] avatar robynm avatar sepehrity avatar thibaultboursier avatar zpchavez 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

use-timer's Issues

problem with firefox browser

hello
thanks to your good library

there is a problem with Firefox browser that seems it is because of that your setTimeout will run before setInterval and then decreasing counter will stuck in second 1 and will never get to zero

I will be happy to inform me when this bug fixed

timer not accurate in mobile

It seems if I lock my phone and get back to the browser, it slows down and after 5 minutes the timer has just counted 20 seconds. How can the timer can be current after the browser becomes active after it being minimized or phone screen locked?

Timer callbacks

onTimeUpdate wrong triggering time

onTimeUpdate function is called on component mount. I think it should be called ONLY when timer status is 'RUNNING'.
Otherwise there should be some checks like:

onTimeUpdate: () => {
  if (timerName.status === 'STOPPED') return;

  ...code
},

Good callback fn to add

  1. onTimeReset
  2. onTimePause
  3. onTimeStop
  4. onTimeStart

Feature request: set initial status

Hi, I was wondering if you would consider adding an optional parameter to initialize the timer with a status other than STOPPED?

I'm saving timer use to a db and would like to be able to return the timer to the last known state in the case of page refresh or network interruption.

I can submit a PR for this if you'd like. Thanks!

Autostart problems

  const { time, start, pause, reset, isRunning } = useTimer({
    initialTime: 3,
    endTime: 0,
    timerType: "DECREMENTAL"
  });

  useEffect(()=>{
    start();
  }, [start])

How can I make timer to autostart only once, when component is rendered? In this case it is restarting every time.

Updating initial time won't update the timer

Hey wassup,

I am changing the initial time when a state is changing ( so it should be re rendernig ) but is not updating to the new time.

The logic behind is, we have an event with start date and end date. So, when the event is not started it shows the timer to the start of the event, and when the event is running it should show the time left until the end of said event.

Also, if you are in another tab the countdown seems to stop, it could be easily fixable checking the time again, but since changing the initial time won't update it's difficult.

`setTime` from the `useTimer` hook?

Hi there. Is there a way to explicitly set the time to a specific point from the component that uses the hook? I have a component that is a video player, and would like to be able to skip +/- 5 seconds.

It seems like this would do the trick, but its not exported.

Missing payload.

dispatch({ type: 'start' });

dispatch requires payload here

Argument of type '{ type: "start"; }' is not assignable to parameter of type '{ type: "advanceTime"; payload: { timeToAdd: number; }; } | { type: "pause"; } | { type: "reset"; payload: { initialTime: number; }; } | { type: "set"; payload: { newTime: number; }; } | { type: "start"; payload: { ...; }; } | { ...; }'. Property 'payload' is missing in type '{ type: "start"; }' but required in type '{ type: "start"; payload: { initialTime: number; }; }'.

wrong time over calculation

Hello thanks for making this libarary.
But I have a question with calculating time over.

 react_1.useEffect(function () {
        if (status !== 'STOPPED' && time === endTime) {
            dispatch({ type: 'stop' });
            if (typeof onTimeOver === 'function') {
                onTimeOver();
            }
        }

I think time >= endTime is more correct.
I have to calc this with frame and ends with xx.000001 like this.
Sometime it doesn't match corrrectly.

Thank you.

Consider using Milliseconds instead of seconds

First of all, I'd like to say, this is a very nice and intelligent library.

Now for the question: Since milliseconds is known to be the basic unit of time, please consider using them instead of seconds.
setInterval and setTimeout were respectful of those basic units, and useTimer should be as well.

Thank you very much and happy coding... :)

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.