clearInterval不重置

时间:2019-03-23 20:56:42

标签: javascript html reactjs setinterval clearinterval

我正在尝试创建一个函数来计算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>

1 个答案:

答案 0 :(得分:3)

您应该使timer变量具有更大的作用域,以便可以从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>