I am trying to execute a function only after 5 seconds, but it execute immediately upon render
Below is my code
class App extends React.Component {
onInactive = (ms, cb) => {
var wait = setTimeout(cb, ms);
document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function () {
clearTimeout(wait);
wait = setTimeout(cb, ms);
};
};
render() {
this.onInactive(5000, alert("Inactive for 5 seconds"));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
export default App;
This is my codesandbox link
In your code, the second parameter is not a function, it's a statement, but setTimeout function expects the first parameter a callback function. Please check the below-working code for it.
import React from "react";
/**
* Add any other events listeners here
*/
// const events = ["mousemove", "click", "keypress"];
class App extends React.Component {
onInactive = (ms, cb) => {
var wait = setTimeout(cb, ms);
document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function () {
clearTimeout(wait);
wait = setTimeout(cb, ms);
};
};
render() {
this.onInactive(5000, () => alert("Inactive for 5 seconds"));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
export default App;