【问题标题】:How can I execute a piece of code for a certain amount of time in JavaScript and React Native?如何在 JavaScript 和 React Native 中执行一段代码一段时间?
【发布时间】:2015-07-05 02:13:44
【问题描述】:

我知道browser timers 存在,但我从未使用过它们,也不知道哪些是我需要使用的。 我正在使用 React Native,我希望代码块仅在 10 秒间隔内执行,间隔的下限应该是第一次单击按钮时。这就是我所拥有的:

  <TouchableHighlight style={styles.button}
        onPress={() => nClicks++}>

        <Text style={styles.buttonText}>
         Tap Here!
        </Text>

        </TouchableHighlight>

动作响应完美,每次单击全局变量的值都会增加 1。我只需要以某种方式找到添加时间间隔约束的方法。有什么想法吗?

【问题讨论】:

  • 我不清楚你想做什么。

标签: javascript reactjs react-native


【解决方案1】:

onPress() 函数中,您可能想要放入setInterval() 方法。你可以试试下面的代码:

var SetIntervalMixin = {
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.map(clearInterval);
    this.intervals.push(setInterval.apply(null, arguments));
  }
};

var App = React.createClass({
  mixins: [SetIntervalMixin], // Use the mixin
  getInitialState: function() {
    return {
      seconds: 0,
      nClicks: 0
    };
  },
  onPress: function( plus ) {
    //this.setState({nClicks: plus});
    this.setInterval(this.codeToExcecute, plus * 1000); // Call a method on the mixin
    this.setState({nClicks: this.state.nClicks + 1});
  },
  codeToExcecute: function() {
    console.log('Im the code to excecute');
  },
  render: function() {
    return (
      <div>
        <p>
          React has been running for {this.state.seconds} seconds. nClick: { this.state.nClicks }
        </p>
        <button onClick={ this.onPress.bind(null, this.state.nClicks + 1) }>Click</button>
      </div>
    );
  }
});

React.render(
  <App />,
  document.getElementById('example')
);

演示:http://jsbin.com/biyibu/2/edit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多