1

i am running a for loop in which it iterates the value of i till 100000 , what i did is used a for loop and inside that used a setstate and i called the state variable in html jsx. Results are getting but the variable changes from 0 to 100000 after some wait.. i want to display the state like 0,1,2,3,4...100000 on very fast manner how can i do that..

code

const [timer, settimer] = useState(0);
for (let i = 0; i < 100000; i++) {
settimer(i)
}
return <h1>{timer}</h1>

as i told i need live updation of the variable, How can i achieve this with reactjs javascript

4
  • How fast, can you please specify? Commented Jun 27, 2021 at 5:01
  • it depends, just imagine using for loop and console.log the output iteration, instead of showing live iteration on console i want to show in html Commented Jun 27, 2021 at 5:02
  • I have the solution, please try it and see if it answers your question. Commented Jun 27, 2021 at 5:05
  • yes , kind of this Commented Jun 27, 2021 at 5:08

2 Answers 2

1

for loop is very fast to see the iterations. I would suggest using a setTimeout, or setInterval to delay the updates. To make it faster, you can reduce the delay to setTimeout.

const {
  useState,
  useEffect
} = React;

const App = (props) => {
  const [timer, setTimer] = useState(0)
  useEffect(() => {
    if (timer < 100000)
      setTimeout(() => setTimer(v => v + 1), 300)
  }, [timer])
  return (
  <div>{timer}</div>
  )
}

ReactDOM.render( <App/> , document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. This is Much better answer, simply use useEffect hook to update the counter.
0

What you need is to update the state on every iteration, loop will finish before state gets updated because state update is asynchronous. What you can do is to wait few milliseconds in each iteration, and update the state. this will re-render the component and you can easily see the counter.

I have created a simple sleep function that will wait for a few seconds.

Here is app.js.

export default function App() {
  const [timer, settimer] = useState(0);
  useEffect(async () => {
    for (let i = 0; i < 100000; i++) {
      await sleep(100);
      settimer(i);
    }
  }, []);
  return <h1>{timer}</h1>;
}

function sleep(seconds) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, seconds);
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.