clearInterval 不重置

clearInterval does not reset

我正在尝试创建一个函数来计算来自 Spotify 的歌曲的时间进度,但我卡在了 clearInterval 函数上。问题是计时器在我尝试重置后一直在加速。我正在使用 Reactjs

首先 运行 intervalToTick 是 1.6 秒,但如果我再次 运行 该函数,它的速度会加倍,并且每次重置都会变得更快(第一次有效)

我的解决方案是因为我使用 mobX 是将 myTimer 添加为商店中的 @observable 然后继续下面的答案

const ticker = function() {
  if (store.timer < 100) {
    store.addToTimer() //mobX store action to add 1+ to the store.timer
  }

};

function progress() {
  store.timer = 0
  let time = Moment()
  let songEnd = Moment().add(1, "minutes")
  const durationToFinnish = Moment.duration(songEnd.diff(time));
  const intervalToTick = 100000 / durationToFinnish.asMilliseconds()

  //Dumb to have it 2 times but cant figure of another way
  var myTimer = window.setInterval(ticker, intervalToTick * 1000);
  clearInterval(myTimer);
  myTimer = window.setInterval(ticker, intervalToTick * 1000);
}
<div className={classes.progressBar} id="progress">
  <div className={classes.innerProgressBar}>
    <span onClick={progress}>{store.timer}%</span><br></br>
  </div>
</div>

您应该使计时器变量具有更高的范围,以便可以从 progressticker 访问它,如果已经有一个 运行,您需要清除间隔,所以你不能同时有多个间隔 运行:

var myTimer = null; // Declared here so it can be used in both functions

const ticker = function () {
  if(store.timer < 100){
    store.addToTimer() //mobX store action to add 1+ to the store.timer
  }      
};

function progress() {        
  store.timer = 0
  let time = Moment()
  let songEnd = Moment().add(1, "minutes")
  const durationToFinnish = Moment.duration(songEnd.diff(time));
  const intervalToTick = 100000 / durationToFinnish.asMilliseconds()  
  // Check to see if there is already a timer running
  if(myTimer){
    clearInterval(myTimer); // Stop the interval   
  }
  myTimer = setInterval(ticker, intervalToTick * 1000);    
}
<div className={classes.progressBar} id="progress">
            <div className={classes.innerProgressBar}>
                <span onClick={progress}>{store.timer}%</span><br></br>
            </div>
        </div>