We are struggling with a strange issue in using setTimeout function in Javascript at the React.
As using codes inside the setTimeout, it runs much slower than running the codes without the setTimeout!
As a comparison, the performance is resulted in:
Using
setTimeout: 1391 ms
without usingsetTimeout: 15 ms
In API callback (eg. axios), the setTimeout version happens as well!
A simple sample code is shown in the following:
codesandbox
Can anyone explain what is happening?
import React, { useState } from "react";
import ReactDOM from "react-dom";
function App() {
const [value, setValue] = useState("");
const [time, setTime] = useState("");
const startSample = () => {
const startTimeStamp = new Date().valueOf();
for (let i = 0; i < 5000; i++) {
setValue(`test-${i}`);
// console.log(`test-${i}`);
}
const endTimeStamp = new Date().valueOf();
setTime(`${endTimeStamp - startTimeStamp}ms`);
};
const handleClick1 = () => {
startSample();
};
const handleClick2 = () => {
setTimeout(() => {
startSample();
});
};
return (
<div style={{ textAlign: "left" }}>
<p>{value || "Please push that button!"}</p>
<div>
<button id="startBtn" onClick={handleClick1}>
Start Normal
</button>
<button id="startBtn1" onClick={handleClick2}>
Start With setTimeout
</button>
</div>
<p>Result: {time}</p>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);