有氧运动应用:清除功能范围内的间隔计时器

时间:2017-03-27 12:41:33

标签: javascript setinterval

这是CodePen上的Cardio应用程序。 http://codepen.io/Mahmoud-Zakaria/pen/vxWzxW?editors=1010 当我想通过停止btn停止有氧运动并清除其在功能范围内引用的间隔时,它不会停止/清除。

 (function() {

  //States
  let i = 5;
  let play = true;

  //DOM
  let cardioSec = document.getElementById('cardio-sec');
  let cardioStart = document.getElementById('cardio-start');
  let cardioStop = document.getElementById('cardio-stop');

  //Render
  function render(el) {
    el.innerHTML = i
  };


  //Audio
  let audio = new Audio("https://raw.githubusercontent.com/mahmoudZakaria90/myCodePenStuff/master/audio/Bepp-beep.mp3");

  //Setup 
  function setInterVals(times, callback) {
    i = times;
    let timer = setInterval(function() {
      console.log(i) //RENDER
      render(cardioSec)
      i--;
      if (i < 1) {
        clearInterval(timer);
        audio.play();
        callback();
      }

    }, 1000)
    return timer;
  }

  function start() {
    setInterVals(5, cardio);
  }

  function cardio() {
    setInterVals(30, rest);
  }

  function rest() {
    setInterVals(15, cardio);
  }

  function stopCardio() {
    clearInterval(setInterVals())
  }

  cardioStart.onclick = start

  cardioStop.onclick = stopCardio

})();

1 个答案:

答案 0 :(得分:-1)

完成:     http://codepen.io/anon/pen/gmdLMr?editors=1010

The "timer" variable was out of the scope, by declaring it as global, you wont have problems ^^