Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
Loop through array with setInterval play button and pause it

I want to loop through a array with a pause and a start button. Right now it automatically plays and I am not sure how to connect the setInterval to the play function and not sure how to stop the interval as everything I try just crashes it. Maybe there is a good a library for doing this as I can imagine this is quite a normal thing to do? If not please help me fix my code, maybe there is better ways to do this if so please tell :) Codesandbox attempt: https://codesandbox.io/s/modern-dream-4kldkg?file=/src/App.js

import "./styles.css";
import { useState } from "react";
export default function App() {
  const array = [1, 2, 3, 5, 6, 7];
  const [current, setCurrent] = useState(0);
  const play = () => {
    setCurrent(current + 1);
  };
  const pause = () => {};
  const reset = () => {
    setCurrent(0);
  };
  var intervalID = setInterval(function () {
    if (current >= array.length) {
      setCurrent(0);
    }
    setCurrent(current + 1);
  }, 5000);

  return (
    <div className="App">
      <button onClick={() => play()}>play</button>
      <br></br>
      <button onClick={() => pause()} style={{ marginTop: "5px" }}>
        Pause
      </button>
      <br></br>
      <button onClick={() => reset()} style={{ marginTop: "5px" }}>
        Reset
      </button>
      <br></br>
      <h1>{array[current]}</h1>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should remove the interval on each render, please see the demo:

import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
  const array = [1, 2, 3, 4, 5, 6, 7];
  const [current, setCurrent] = useState(0);
  const [paused, setPaused] = useState(true);
  const play = () => {
    setPaused(false);
  };
  const resume = () => {
    setPaused(false);
  };
  const pause = () => {
    setPaused(true);
  };
  const reset = () => {
    setCurrent(0);
    setPaused(true);
  };

  useEffect(
    function () {
      var timeout;
      if (!paused) {
        timeout = setTimeout(function () {
          const next = current < array.length - 1 ? current + 1 : 0;
          setCurrent(next);
        }, 1000);
      }
      return function () {
        clearTimeout(timeout);
      };
    },
    [paused, current, array.length]
  );

  return (
    <div className="App">
      <button onClick={() => play()}>play</button>
      <br></br>
      <button onClick={() => pause()} style={{ marginTop: "5px" }}>
        Pause
      </button>
      <button onClick={() => resume()} style={{ marginTop: "5px" }}>
        Resume
      </button>
      <br></br>
      <button onClick={() => reset()} style={{ marginTop: "5px" }}>
        Reset
      </button>
      <br></br>
      <h1>{array[current]}</h1>
    </div>
  );
}

https://codesandbox.io/s/throbbing-cdn-4c77nr

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda