useIntervalWhen

About

Sets an interval immediately when a condition is true

Examples

Basic example

import { useIntervalWhen } from "rooks";
import { useState } from "react";

function App() {
  const [value, setValue] = useState(0);
  const [when, setWhen] = useState(false);

  useIntervalWhen(
    () => {
      setValue(value + 1);
    },
    1000, // run callback every 1 second
    when // start the timer when it's true
  );

  return (
    <div
      style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
    >
      <h1>Rooks: useIntervalWhen example</h1>
      <h2>Value: {value}</h2>
      <button onClick={() => setWhen(true)}> Start interval </button>
    </div>
  );
}

export default App;

Fire callback instantly and not wait for first interval to finish

import { useIntervalWhen } from "rooks";
import { useState } from "react";

function App() {
  const [value, setValue] = useState(0);
  const [when, setWhen] = useState(false);

  useIntervalWhen(
    () => {
      setValue(value + 1);
    },
    1000, // run callback every 1 second
    when, // start the timer when it's true
    true // no need to wait for the first interval
  );

  return (
    <div
      style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
    >
      <h1>Rooks: useIntervalWhen example</h1>
      <p>
        Notice how the first increment is instantly after interval is enabled.
        If n intervals run, the callback fires n+1 times.
      </p>
      <h2>Value: {value}</h2>
      <button onClick={() => setWhen(true)}> Start interval </button>
    </div>
  );
}

export default App;

Arguments

ArgumentTypeDescriptionDefault value
callbackfunctionFunction be invoked after each interval durationundefined
intervalDurationnumberDuration in milliseconds after which callback is invoked0
whenbooleanOnly start timer when when is truetrue
startImmediatebooleanShould the timer start immediately or nofalse

Returned Object

No return value.

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel