N
N
n1ksON2021-02-28 00:23:04
React
n1ksON, 2021-02-28 00:23:04

How to make a repeating animation?

It is necessary to make a change of style in a block that repeats with a certain interval.
I have an array with objects in which the style is registered. It is necessary to change the style in the block with a certain frequency.

Here's what I got:

import React, { useEffect, useState } from "react";

const Result = ({ properties, time }) => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    let timerId = setTimeout(
      () => (count < 2 ? setCount((prev) => ++prev) : setCount(0)), // count всегда меньше 3х
      `${time}000`
    );
  }, [count, time]);
  let styles = [];
  for (let i = 0; i < properties.length; i++) {
    styles.push({
      color: `${properties[i].color}`,
    });
  }
  return (
    <div>
      <div
        className="banner"
        style={styles[count]}
      />
    </div>
  );
};

export default Result;


The code works until properties or time change. Then, as I understand it, a new timer is created and everything breaks.
If I understand correctly, after changing properties or time, you need to reset the running timer, but how can I do this? Create a new useEffect? But how to access the interval from the already existing useEffect?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-02-28
@n1ksON

But how to access the interval from the already existing useEffect?

effect cleaning

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question