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

177
Views
Reactjs: setTimeout not working as expected

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
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!