首页 > 解决方案 > 不能让函数再次运行

问题描述

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

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);
    }
}

标签: javascriptdom

解决方案


现代 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>


推荐阅读