Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
How can I make this interval stop when it reaches the end of the array?

I am trying to make a little animation with an array where it kind of types out my name like in a command prompt. This is my first time using hooks in react so I'm kind of lost. I'd like to make it so that the interval stops at "Felipe Garcia Diaz" but instead of it stopping the interval just makes my text disappear and it continues to run in the background. What am i doing wrong exactly?

HooksExample.jsx

import React, {useState} from 'react';
import socket from './socket';

function Main(props) {
    let introArray = ["_","F_", "Fe_", "Fel_", "Feli_", "Felip_", "Felipe_", "Felipe _", "Felipe G_", "Felipe Ga_", "Felipe Gar_", "Felipe Garc_", "Felipe Garci_", "Felipe Garcia_"];

    let [myName, setName] = useState(introArray);
    let [climber, setClimber] = useState(0);

    let block = false;
    if(block === false) {
        let climbArray = () => {
            setClimber(climber += 1);
            if(climber === introArray.length) {
                block = true;
                console.log('dead');
            }
            console.log('live', climber);
        }
        setInterval(climbArray, 200);
    }
    return (
        <React.Fragment>
            <h1>{myName[climber]}</h1>
        </React.Fragment>
    );
}


export default Main;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Some feedback:

  • to clear an interval, you need to store the value returned from setInterval() and pass it into clearInterval()
  • triggering an interval and updating state are side effects so should be wrapped inside useEffect()
  • for useEffect() to access latest climber value, it must be in the dependency array like [climber]
  • myName does not need to be in state because its value can be derived from introArray
  • I replaced introArray with string for simplicity's sake, if you really want to use array then corresponding JSX is <h1>{introArray[climber]}</h1>
import React, {useState, useEffect} from 'react';
import "./styles.css";

export default function App() {
  const intro = "Felipe Garcia_";
  const [climber, setClimber] = useState(0);

  useEffect(()=>{
    const interval = setInterval(() => {
      if (climber === intro.length) {
        console.log('clearing');
        clearInterval(interval);
      } else {
        setClimber((val) => val + 1);
      }
    }, 200);
    // clean up interval on unmount
    return (()=>{
      clearInterval(interval);
    });
  }, [climber]);

  return (
      <React.Fragment>
        <h1>
          {intro.substring(0, climber)}_
        </h1>
      </React.Fragment>
  );
}

Working example

about 4 years ago · Juan Pablo Isaza Relatório

0

import React, {useState} from 'react';
import socket from './socket';

function Main(props) {
    let introArray = ["_","F_", "Fe_", "Fel_", "Feli_", "Felip_", "Felipe_", "Felipe _", "Felipe G_", "Felipe Ga_", "Felipe Gar_", "Felipe Garc_", "Felipe Garci_", "Felipe Garcia_"];
let interval 
    let [myName, setName] = useState(introArray);
    let [climber, setClimber] = useState(0);

    let block = false;
    if(block === false) {
        let climbArray = () => {
            setClimber(climber += 1);
            if(climber === introArray.length) {
                block = true;
                if(interval !== undefined){
                  clearInterval(interval)
                }
              
                console.log('dead');
                
            }
            console.log('live', climber);
        }
        interval = setInterval(climbArray, 200);
    }
    return (
        <React.Fragment>
            <h1>{myName[climber]}</h1>
        </React.Fragment>
    );
}


export default Main;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda