无法使功能再次运行

时间:2019-04-24 09:36:17

标签: javascript dom

我做了一个计时器,它将达到零。 当它达到零时,使计时器再次运行。 计时器返回到起始编号,但不再运行。 当我再次调用它时,数字也开始跳跃。 代码:

var timerPlace = document.getElementById('timer');
var timerP = document.getElementById('timerHard');
var stopTimer;
var toStop;

function timeMed() {
    console.log('im in!')

    var counter = 0;
    var timeLeft = 5;

    timerPlace.innerHTML = '00:45';

    function timeIt() {
        console.log('here')
        counter++
        timerPlace.innerHTML = convertSeconds(timeLeft - counter); 

        if (timerPlace.innerHTML == '00:00') {
            clearInterval(stopTimer);
            resetExercise();
            timeMed();
        }

    }
    function convertSeconds(s) {
        var sec = s % 60;
        var min = Math.floor((s % 3600) / 60);

        return ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
    }

    if (!stopTimer) {
        stopTimer = setInterval(timeIt, 1000);
    }
}

2 个答案:

答案 0 :(得分:0)

仅在未设置setInterval()时呼叫stopTimer。但是,在倒计时完成后,stopTimer仍设置为旧间隔计时器的ID,因此您无需重新启动它。调用clearInterval()时应清除变量。

    if (timerPlace.innerHTML == '00:00') {
        clearInterval(stopTimer);
        stopTimer = null;
        resetExercise();
        timeMed();
    }

答案 1 :(得分:0)

现代ES6方法和最佳实践。

我决定抓住这个机会,并考虑到Javascript的最佳实践来对代码进行一些重构。

我添加了注释,以解释代码和工程注意事项。

计时器的基准来自此处的出色答案:https://stackoverflow.com/a/20618517/1194694

// Using destructuring on the paramters, so that the keys of our configuration object, 
// will be available as separate parameters (avoiding something like options.duraitons and so on.
function startTimer({duration, onUpdate , infinite}) {
    let timer = duration, minutes, seconds;
    let interval = setInterval(function () {
        minutes = parseInt(timer / 60);
        seconds = parseInt(timer % 60);
        
        // you can also add hours, days, weeks ewtc with similar logic
        seconds = seconds < 10 ? `0${seconds}` : seconds;
        minutes = minutes < 10 ? `0${minutes}` : minutes;

        
        // calling your onUpdate function, passed from configuraiton with out data
        onUpdate({minutes, seconds});

        if (--timer < 0) {
        	// if infinite is true - reset the timer
          if(infinite) {
            timer = duration;
          } else {
            // Clearing the interval + additonal logic if you want
            // I would also advocate implementing an onEnd function,  
            // So that you'll be able to decide what to do from configuraiton.
            clearInterval(interval);
          }
       	}
        
    }, 1000);
}

const duration = 5;
const displayElement = document.querySelector("#timer");
startTimer({
  duration,
  onUpdate: ({minutes, seconds}) => {
    // now you're not constraint to rendering it in an element,
    // but can also Pass on the data, to let's say your analytics platform, or whatnot
    displayElement.textContent = `${minutes}:${seconds}`;
  },
  infinite: true
});
<div id="timer">
</div>