Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including @react-corekit/use-interval with all npm packages installed. Try it out:

require("react/package.json"); // react is a peer dependency. var useInterval = require("@react-corekit/use-interval")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

@react-corekit/use-interval v1.1.1

React Hook implementation for setInterval()

@react-corekit/use-interval

React Hook implementation for setInterval()

NPM JavaScript Style Guide

Install

npm install --save @react-corekit/use-interval
yarn add @react-corekit/use-interval

Syntax

useInterval(func, delay);

Parameters

func

A function to be executed every delay milliseconds. The function is not passed any arguments, and no return value is expected.

delay

The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function.

Usage

Visit: https://react-corekit.github.io/use-interval/ for a minimalistic live demo.

import React, { useState } from "react";

import { useInterval } from "@react-corekit/use-interval";

const Counter = () => {
  const [count, setCount] = useState(0);

  useInterval(() => {
    setCount(count + 1);
  }, 1000);

  return <h1>{count}</h1>;
};

Pausing and Reseting the counter example

const App = () => {
  const [delay] = useState(1000);
  const [count, setCount] = useState(0);
  const [isRunning, setIsRunning] = useState(true);

  useInterval(
    () => {
      setCount(count + 1);
    },
    isRunning ? delay : null
  );

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsRunning(!isRunning)}>
        {isRunning ? "Stop" : "Start"}
      </button>
    </div>
  );
};

Additional documentation

Window/GlobalScope setInterval Reference

Making setInterval Declarative with React Hooks

Credits

Based on Dan Abramov's post "Making setInterval Declarative with React Hooks".

License

MIT - glongh

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free