Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

I'm currently trying to implement a button long-press/hold for both mouse and touch events so that you can simply hold the button and have the component just keep increasing the element value until you let go. I'm not sure why, but even setting the state out of the loop logic, it still causes a freeze/infinite loop to occur. Maybe I need to circumvent this entirely and use some timing logic like 500ms?

Thanks in advance!

JavaScript
export default class Number extends Component {
  static propTypes = {
    onChange: PropTypes.func.isRequired
  }
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.doneChange = this.doneChange.bind(this);
    this.state = {
      i: 0,
      pressed: false
    };
  }
  handleChange(i) {
    this.doneChange(true);
    let I = this.state.i;
    while (this.state.pressed) {
      I += i;
      if (I > 150) {
        I = 150;
      }
      if (I < 0) {
        I = 0;
      }
    }
    this.setState({
      i: I
    }, () => {
      this.props.onChange(this.state.i);
    });
  }
  doneChange(isPressed) {
    this.setState({
      pressed: isPressed
    });
  }


EDIT: For some odd reason, the edit here doesn't show the render code in code wrapping, so here here you go -

HTML
render() {
  const styles = require('./Number.scss');
  return (
    <div className={styles.number}>
      <button
        ><span>-</span></button>
      <div className={styles.numeral}>{this.state.i}</div>
      <button
        ><span>+</span></button>
    </div>);
}
Posted
Updated 24-Sep-15 7:48am
v3
Comments
PIEBALDconsult 24-Sep-15 14:07pm    
You may need to perform the resize on a separate thread so the UI thread can respond to the mouse-up event.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900