setTimeout不会执行

时间:2017-11-10 14:40:23

标签: javascript react-native

我正在使用react native来制作应用程序。我需要等待十秒钟,然后在屏幕上进行重定向。这是我的代码:

onPressEnter() {

      setTimeout(onPressEnter(), 5000);

      //////Redirecting
        changePage("Error");
    }

但是,我发现的超时命令都没有显示,或者它们给我一个错误:

  

无法找到onPressEnter

我应该提一下,这个方法通过屏幕上的按钮调用。

你能帮我解决一下如何正确实现超时吗?

3 个答案:

答案 0 :(得分:1)

以下示例可能有所帮助。执行onPressEnter()函数时,首先检查是否已有从先前执行运行的计时器。如果是这样,什么也不做。否则,设置10秒的超时,然后运行一个调用changePage()函数的函数。



class MyComponent extends React.Component {

  onPressEnter = () => {
    if(this.timer > 0) return;
    this.timer = setTimeout(() => {
      this.changePage("Error");
      this.timer = null;  //not necessary if you are unmounting the component
    }, 10000);
  }

  changePage = (page) => {
    console.log("redirecting to " + page);
  }

  render() {
    return <button onClick={this.onPressEnter}>Redirect</button>
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("app"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果向函数声明添加函数并从setTimeout函数中删除括号,则代码应该有效:

&#13;
&#13;
function onPressEnter() {
    setTimeout(onPressEnter, 5000);
    console.log('enter pressed');
}

onPressEnter();  // start the timeout loop going
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

尝试在匿名函数中添加它。

onPressEnter() {
  setTimeout(function() {
    onPressEnter()
  }, 5000); 
  //////Redirecting
  changePage("Error");
}
相关问题