Не могу сделать функцию снова запустить - PullRequest
0 голосов
/ 24 апреля 2019

Я сделал таймер, который достигнет нуля. и когда он достигнет нуля, таймер снова запустится. таймер возвращается к начальному номеру, но не запускается снова. также, когда я звоню снова, цифры просто начинают прыгать. код:

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 голосов
/ 24 апреля 2019

Современный подход ES6 и лучшие практики.

Я решил рискнуть и немного изменить свой код с учетом лучших практик Javascripts.

Я добавил комментарии, которые объясняют код и технические соображения.

Базовая линия для таймера взята из отличного ответа здесь: 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>
0 голосов
/ 24 апреля 2019

Вы звоните setInterval() только тогда, когда stopTimer не установлен. Но после завершения обратного отсчета stopTimer по-прежнему устанавливается на идентификатор старого таймера, поэтому вы не перезапустите его. Вы должны очистить переменную при вызове clearInterval().

    if (timerPlace.innerHTML == '00:00') {
        clearInterval(stopTimer);
        stopTimer = null;
        resetExercise();
        timeMed();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...