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

251
Views
why Generating random data using setInterval in react js not Generating after certain seconds?

i am trying to generate random data in react.but data start to move like after 1 seconds 1 entry then after another second 5 entries then 26 then 126 and so on mean after every second data is exponentially generate.But i want to generate only 1 record after 1 second

function App() {

const [pktD,setPktD]=useState({
    chid:0,
    peakVal:0,
})
const dataGen=setInterval( function(){
setPktD({...pktD,chid:Math.random()*253});
setPktD({...pktD,peakVal:Math.random()*10000})

},5000)
console.log(dataGen);
return (
<></>
);
}

I also try to implement in custom hook but facing same problem.First entry generate after 5 second but after that data generate random intervals. myCustom hook is below i also tried this.

import React ,{useState} from "react"


function DataGenerator(){
const [pktD,setPktD]=useState({
    chid:0,
    peakVal:0
})
 const dataGen=function(){
setPktD({...pktD,chid:Math.random()*253});
setPktD({...pktD,peakVal:Math.random()*10000})
return pktD
}
 return [dataGen];
}
export default DataGenerator;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do something like this

import React, { useState, useEffect } from "react";

function App() {
  const [pktD, setPktD] = useState({
    chid: 0,
    peakVal: 0
  });
  useEffect(() => {
    const dataGen = setInterval(function () {
      // setPktD({ ...pktD, chid: Math.random() * 253 });
      // setPktD({ ...pktD, peakVal: Math.random() * 10000 });
      setPktD((prevState) => ({...prevState, chid: Math.random() * 253, peakVal: Math.random() * 10000}));
    }, 5000);

    return () => {
      clearInterval(dataGen);
    }
  }, []);
  console.log(pktD);
  return <></>;
}

export default App;
about 4 years ago · Juan Pablo Isaza Report

0

because you are not clearning interval along also use in useEffect beacuse its running async.

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!