简体   繁体   English

Reactjs:setTimeout 未按预期工作

[英]Reactjs: setTimeout not working as expected

I am trying to execute a function only after 5 seconds, but it execute immediately upon render我试图仅在 5 秒后执行一个函数,但它在渲染时立即执行

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.在您的代码中,第二个参数不是函数,而是语句,但是 setTimeout 函数需要第一个参数是回调函数。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM