如何在React组件中运行一个计时器60秒,并每5秒调用一次Redux操作

时间:2018-04-01 09:54:04

标签: javascript reactjs redux

我有一个反应容器,我想运行一个60秒的计时器,每5秒我想发送一个动作。此操作调用api并返回一些结果。 还有一件事需要处理,假设我的动作在第3次呼叫后返回错误,即15秒后,那么我怎么能在此后停止计时器。

handleSimulateButton = (e) => {
    /*
        Once I click on Simulate button, I want the below codes to run 
        exactly for 60 seconds
    */

    function runFor60seconds(){
        /*anyRequestFails takes boolean value and I can easily determine 
          its value.
        */
        if(anyRequestFails){
            //stop timer and exit from function
        }

        // I want to this every 5 secs
        else{
            //Calculations
            let params = calculatedvalue
            this.props.callAPI(params)
        }
    }
}

我怎样才能做到这一点?我正在学习React和redux并且无法弄明白。上面的代码片段只是我所需代码的伪代码。

2 个答案:

答案 0 :(得分:1)

Window.setInterval()可用于创建间隔。

Window.clearInterval()可用于清除间隔。

// Eg.
class Eg extends React.Component {
  
  // Single interval.
  singleInterval = () => {
    
    // Prevent duplicates.
    clearInterval(this.interval)
    
    // Set timeout.
    const fiveSeconds = 1000 * 5
    this.timeout = new Date()*1 + fiveSeconds
    
    // Create Interval.
    this.interval = setInterval(() => {
    
      // Interval logic ..
      console.log('Single Interval: 1 second ..')
      
      
      if (new Date() > this.timeout) {

        // Interval complete.
        console.log('Interval complete.')

        // Tidy up.
        clearInterval(this.interval)

      }

    }, 1000)
  }
  
  // Concurrent interval.
  concurrentInterval = () => {
  
    // Set timeout.
    const fiveSeconds = 1000 * 5
    const timeout = new Date()*1 + fiveSeconds
    
    // Create Interval.
    const ID = setInterval(() => {
    
      // Interval logic ..
      console.log(`Interval ${ID}`)
      
      
      if (new Date() > timeout) {

        // Interval complete.
        console.log(`${ID} complete.`)

        // Tidy up.
        clearInterval(ID)

      }

    }, 1000)
    
  }
  
  // Render.
  render = () => (
    <React.Fragment>
      <button onClick={this.singleInterval}>Single Interval</button>
      <button onClick={this.concurrentInterval}>Concurrent Interval</button>
    </React.Fragment>
  )
}

// Mount.
ReactDOM.render(<Eg/>, document.querySelector('#root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

答案 1 :(得分:1)

要在JavaScript中使用计时器,您可以使用:

setInterval();

在这种情况下,您希望将间隔分配给变量,以便您可以像这样取消它;

var minute = 60000;
var myInterval = setInterval(function(){ ... }, minute);

clearInterval(myInterval);

要跟踪失败的请求,您需要在函数范围之外分配一个变量,以便像这样调用您的api;

var failedAmount = 0;

function apiRequest(){ 
    if(failedAmount === 3) clearInterval(myInterval);
    ... 
    onFail = () => failedAmount++;
};

有关间隔的更多信息,请参阅: Intervals