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

221
Vistas
Settimeout in next js/react
let i = 0

function pollDOM() {     
  console.log(i)

  i++

  setTimeout(pollDOM, 3000) // try again in 300 milliseconds
}

pollDOM()

The above function use to run every 3 second, output is like:

1 

// wait 3 seconds

2 

// wait 3 seconds

3 

// wait 3 seconds

4 

// wait 3 seconds, and so on...

But in Next.js, it produces a result as:

1
2 

// wait for 3 seconds

3
4

// wait for 3 seconds

5
6

// wait for 3 seconds, and so on...

Why it is produced this way, two numbers together?

How can I achieve that that I am achieving in normal JavaScript?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Bacause when your component is rendered for a second time you're adding the setTimeout again. You have to clear your timeout and use useEffect to set it only once, when the component is crated. Also, use setInteval instead of recursive functions when you have to repeat something every x seconds. Try:

useEffect(() => {
  let i = 0;

  function pollDOM() {
    console.log(i);
    i++;
  }
  
  const interval = setInterval(pollDOM, 3000);
  
  return () => clearInterval(interval);
}, [])
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