npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zaki1001/react-interval

v1.0.0

Published

React hook for using self-correcting setInterval, augmented by management methods (start, stop, isActive) and also using React Class Based Component

Downloads

45

Readme

:watch: 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>
    );
};

Usage For React Class Based Components

Quickstart

Start counting on render

import { ReactInterval } from 'react-interval';

const App = React.createClass({
  getInitialState() {
    return {count: 0};
  },

  render() {
    const {count} = this.state;

    return (
      <div>
        {count}
        <ReactInterval timeout={1000} enabled={true}
          callback={() => this.setState({count: this.state.count + 1})} />
      </div>
    );
  }
});

Full example

Change timeout on the fly, start and stop counting

import React from 'react';
import ReactDOM from 'react-dom';
import { ReactInterval } from 'react-interval';

const App = React.createClass({
  getInitialState() {
    return {
      enabled: false,
      timeout: 1000,
      count: 0
    };
  },

  render() {
    const {timeout, enabled, count} = this.state;

    return (
      <div>
        <ReactInterval {...{timeout, enabled}}
          callback={() => this.setState({count: this.state.count + 1})} />

        <input type="number" step="200" min="200" max="5000" value={this.state.timeout}
          onChange={({target: {value}}) => this.setState({timeout: parseInt(value, 10)})} />&nbsp;

        <button disabled={enabled} onClick={() => this.setState({enabled: true})}>
          Start</button>&nbsp;

        <button disabled={!enabled} onClick={() => this.setState({enabled: false})}>
          Stop</button>&nbsp;

        {count}
      </div>
    );
  }
});

const appRoot = document.createElement('div');
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);

Options

callback: PropTypes.func.isRequired

Function repeatedly called after timeout

enabled: PropTypes.bool (default: false)

Should start timer?

timeout: PropTypes.number (default: 1000)

Timeout before each callback call

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