Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!