繁体   English   中英

递归`setTimeout`没有以预期的方式参与

[英]Recursive `setTimeout` doesn't engage in expected way

我有一个范围输入字段,其数值在我拖动时会发生变化:

在此输入图像描述

当我一直向右拖动时,输入的最大值会增加。 然后,当我释放(onMouseUp或onTouchEnd)时,最大值减小,以便我可以进一步拖动并通过拖动继续增加最大值:

在此输入图像描述

当我一直向左拖动时,输入的最小值减小。 然后,当我释放(onMouseUp或onTouchEnd)时,最小值增加,以便我可以进一步拖动并通过拖动继续减少min:

在此输入图像描述

我应该总是有99的范围。例如,如果我将最大值增加到530,则最小值将为431。

问题:

我有两个递归setTimeout设置为minmax更改。

当用户首先拖动到任何一侧时,该数字应该慢慢改变。 如果他们持有2秒钟,数字应该会更快地增加。 相关代码:

// After arbitrary period, increase the rate at which the max value increments
this.fasterChangeStake = setTimeout(() => {
  this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
}, 2000);

这是第一次工作。 但随后,它首先锁定更快的超时:

在此输入图像描述

尽管我在拖动结束时清除了超时:

clearTimeout(this.increaseStakeLimits);
clearTimeout(this.decreaseStakeLimits);
clearTimeout(this.timer);

为什么第一个(较慢的)超时没有吸引力?

Codepen: https ://codepen.io/alanbuchanan/pen/NgjKMa editors = 0010

JS:

const {observable, action} = mobx
const {observer} = mobxReact
const {Component} = React

@observer
class InputRange extends Component {
  constructor() {
    super();
    this.INITIAL_STAKE_CHANGE_TIMEOUT = 200;
    this.FAST_STAKE_CHANGE_TIMEOUT = 20;
    this.SNAP_PERCENT = 10;
    this.increaseStakeLimits = this.increaseStakeLimits.bind(this);
    this.decreaseStakeLimits = this.decreaseStakeLimits.bind(this);
  }

  @observable min = 0;
  @observable max = 99;
  @observable stakeChangeTimeout = this.INITIAL_STAKE_CHANGE_TIMEOUT;
  @observable isIncreasing = false;
  @observable isDecreasing = false;
  @observable stake = 0;
  @action updateStake = (amount) => {
    if (amount > -1) {
      this.stake = amount
    }
  };

  increaseStakeLimits() {
    const { updateStake } = this;

    this.max = this.max += 1;
    this.min = this.max - 99
    updateStake(this.max);

    // After arbitrary period, increase the rate at which the max value increments
    this.fasterChangeStake = setTimeout(() => {
      this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
    }, 2000);

    // Recursive call, like setInterval
    this.timer = setTimeout(this.increaseStakeLimits, this.stakeChangeTimeout);
    this.isIncreasing = true;
  }

  decreaseStakeLimits() {
    console.warn('this.stake:', this.stake)
    const { stake } = this
    const { updateStake } = this;

    this.min = this.min -= 1;
    this.max = this.min + 99
    updateStake(this.min);

    // After arbitrary period, increase the rate at which the max value increments
    this.fasterChangeStake = setTimeout(() => {
      this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
    }, 2000);

    // Recursive call, like setInterval
    this.timer = setTimeout(this.decreaseStakeLimits, this.stakeChangeTimeout);
    this.isDecreasing = true;

  }

  handleStakeChange = e => {
    clearTimeout(this.increaseStakeLimits);
    clearTimeout(this.decreaseStakeLimits);
    clearTimeout(this.timer);

    const { updateStake } = this;
    const { stake } = this;

    const val = Number(e.target.value)

    // User has scrolled all the way to the right
    if (val >= this.max) {
      console.warn("scrolled to right")
      this.increaseStakeLimits();

    // User has scrolled all the way to the left
    } else if (val <= this.min) {
      console.warn("scrolled to left")
      if (val > -1) {
        this.decreaseStakeLimits();
      }
    } else {
      updateStake(val);
    }
  };

  handleRelease = () => {
    console.warn("RANGE:", this.max - this.min)
    console.warn("released");
    clearTimeout(this.fasterChangeStake);
    clearTimeout(this.timer);
    // Reset the timeout value to the initial one
    this.stakeChangeTimeout = this.INITIAL_STAKE_CHANGE_TIMEOUT;
    this.SNAP_PERCENT = 10
    const snapAmount = this.SNAP_PERCENT
    if (this.isIncreasing) {
      this.max += snapAmount
    }

    if(this.isDecreasing && this.min > 0) {
      this.min -= snapAmount
    }

    this.isIncreasing = false;
    this.isDecreasing = false;
  };

  render() {
    const { stake } = this;

    const style = {
      backgroundSize:
        (stake - this.min) * 100 / (this.max - this.min) + "% 100%"
    };

    return (
      <div className="rangeContainer">
        <div>{this.stake}</div>
        <div className="inputContainer">
          <input
            id="betRangeId"
            type="range"
            min={this.min}
            max={this.max}
            step="1"
            ref={input => {
              this.textInput = input;
            }}
            value={this.stake}
            onChange={this.handleStakeChange}
            onTouchEnd={this.handleRelease}
            onMouseUp={this.handleRelease}
            style={style}
          />
        </div>
      </div>
    );
  }
}

ReactDOM.render(<InputRange />, document.getElementById('root'))

这是一个非常聪明的用户界面!

increaseStakeLimits()在用户将滑块保持在最右侧的整个时间内连续触发,因此您不断设置新的setTimeouts以this.stakeChangeTimeout更改this.stakeChangeTimeout更改为this.stakeChangeTimeout后的较短间隔(并不断为this.fasterChangeStake设置新值)。 即使在handleRelease()尝试将间隔重置为更长的值之后,这些仍会继续触发,这会强制它返回到快速模式,直到所有它们都被触发( handleRelease()clearTimeout仅捕获其中一个。)

您可以通过仅设置一次超时来解决此问题:

if (!this.fasterChangeStake) {
  this.fasterChangeStake = setTimeout(() => {
    this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
    this.fasterChangeStake = false; // <-- also do this in handleRelease() after clearing the timeout
  }, 2000);
}

https://codepen.io/anon/pen/OgmMNq?editors=0010

暂无
暂无

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

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