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

148
Vistas
Why is this function behaving differently on calling first time and second time in React js?

I am trying to implement a turn by turn navigation with mapbox gl js in react,I am trying to make the marker positon update smooth instead of it being teleported.So to perform the animation I am trying to call a function recursively but for some reason the same function behaves differently when called second time compared to the first,code snippet is given below (logs)

const animateMarker = () => {
  setSteps(0);
  const lng = endlongitude - longitude;
  const lat = endlatitude - latitude;
  setDeltaLng(lng / numDeltas);
  setDeltaLat(lat / numDeltas);

  makeAnimation();
};


const makeAnimation = () => {
  let t = 0;

  setLatitude(latitude + deltaLat);
  setLongitude(longitude + deltaLng);
  let lat = 13.0547712;
  let lng = 80.1144832;

  const loop = () => {
    setTimeout(() => {
      lng = lng + deltaLng;
      lat = lat + deltaLat;
      console.log(lat);
      t++;
      usermarker ? .setLngLat([lng + deltaLng, lat + deltaLat]);
      if (t != numDeltas) {
        loop();
      }
    }, 100);
  };
  loop();
};



<!-- end snippet -

<!-- begin snippet: js hide: false console: true babel: false -->

> I am using normal JS variables instead of react useState because useState doesnt work in 
recursive state updation.This behaviour is very weird ,also I have attached the console log for the variable showing both functions running but behaving differently
 <button
        className="nav-btn"
        onClick={(e) => {
          animateMarker();
        }}
      >
        navigate
      </button>

->

`

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

0

Your function makeAnimation captured the value of the state values when you first called it, so it won't update the delta variables.

Consider using the functional form of the setState hook.

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