Giter Club home page Giter Club logo

react-interval-hook's Introduction

⌚ React Interval Hook

React hook for using self-correcting setInterval, augmented by management methods (start, stop, isActive)

Build Status codecov npm type definitions npm bundle size npm GitHub

  • Self-correcting (explanation)
  • Manageable (start, stop, isActive)
  • Thoroughly tested

Install

yarn add react-interval-hook

or

npm install --save react-interval-hook

Basic Usage

import React from 'react';
import { useInterval } from 'react-interval-hook';

const Example = () => {
    useInterval(() => {
        console.log('I am called every second');
    });
};

Advanced usage

Hook can accept various config option as well as return methods that allow you to control it behaviour.

Definition

useInterval(callback [, intervalMs] [, options]): { start, stop, isActive }

Example

Edit react-interval-hook

import React, { useState } from 'react';
import { useInterval } from 'react-interval-hook';

const AdvancedExample = () => {
    const { start, stop, isActive } = useInterval(
        () => {
            console.log('Callback every 500 ms');
        },
        500,
        {
            autoStart: false,
            immediate: false,
            selfCorrecting: false,
            onFinish: () => {
                console.log('Callback when timer is stopped');
            },
        }
    );
    const [active, setActive] = useState(isActive());
    const [triggerFinishCallback, setTriggerFinishCallback] = useState(true);

    return (
        <div>
            <button type="button" onClick={start} id="start">
                Start
            </button>
            <button type="button" onClick={() => stop(triggerFinishCallback)} id="stop">
                Stop
            </button>
            <button type="button" onClick={() => setActive(isActive())} id="checkActive">
                Check active
            </button>
            <div id="active">Active: {active ? 1 : 0}</div>
            <div>
                <label htmlFor="trigger-finish-callback">
                    <input
                        id="trigger-finish-callback"
                        type="checkbox"
                        defaultChecked={triggerFinishCallback}
                        onChange={() => setTriggerFinishCallback(current => !current)}
                    />
                    Trigger finish callback
                </label>
            </div>
        </div>
    );
};

Options

Name Type Default Description
autoStart boolean true Start interval timer right after component is mounted
immediate boolean false Trigger callback immediately after timer is started
selfCorrecting boolean true Self correct time intervals between subsequent callback invocations to reflect actual time elapsed (setInterval and setTimeout are not accurate and tend to drift).
onFinish Function () => {} Called after timer is stopped (by stop method or component unmount)

Management methods

useInterval hook return object with various management methods

Name Arguments Return Description
start None void Starts timer when autoStart is set to false or after timer was stopped using stop method
stop [optional] triggerFinishCallback
- Type: boolean
- Default: true
void Stops timer (not pause) after it was started using either autoStart option or start method
isActive None boolean Return current timer status - is it running or not

License

MIT © minwork

react-interval-hook's People

Contributors

minwork avatar

Watchers

 avatar

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.