使用开始按钮烹饪倒数计时器

时间:2018-05-07 18:23:29

标签: button timer countdown countdowntimer

我正在创建一个应用程序来帮助用户烹饪面食。用户将选择各种选项,最后一步将根据他们选择的选项创建计时器。 (示例:选择意大利面条面条,al dente将导致10分钟计时器)为了调试代码,我删除了我的代码来计算cookTime变量并将其设置为等于10(分钟)以使更容易变细。这是我的代码:

<script>
	
    var cookTime = 10;
    
	$("#timerButton").on("click", function(event){
		event.preventDefault();
		document.getElementById('timer').innerHTML = Number(cookTime) + ":" + 00;
		startTimer();
	});

	function startTimer() {
	  var presentTime = Number(cookTime) + ":" + 00;
	  var timeArray = presentTime.split(/[:]+/);
	  var m = timeArray[0];
	  var s = checkSecond((timeArray[1] - 1));
		  if(s===59){
			  m=m-1;
		  } //if(m<0){alert('timer completed')}

	  document.getElementById('timer').innerHTML =
		m + ":" + s;
	  setTimeout(startTimer, 1000);
	}

	function checkSecond(sec) {
	  if (sec < 10 && sec >= 0){ // add zero in front of numbers < 10
		  sec = "0" + sec;
	  } 
	  if (sec < 0){
		  sec = "59";
	  }
	  return sec;
	}
</script>
p {
  text-align: center;
  font-size: 60px;
  margin-top:50px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div id="timer"></div>
  <a href="#" id="timerButton">Start Timer</a>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您在功能中设置分钟和秒变量,以便每次都获得相同的值。

var cookTime = 1;
var presentTime = Number(cookTime) + ":00";
var timeArray = presentTime.split(/[:]+/);
// set your minute and second counters
var min = parseInt(timeArray[0]);
var sec = parseInt(timeArray[1]);

$("#timerButton").on("click", function(event){
    event.preventDefault();
    // show initial time (using jquery since you're already using it for your click function)
    $('#timer').html(presentTime);
    startTimer(min, sec);
});

function startTimer(m, s) {
  s--;
  if (s<0) {
    s = 59;
    m--;
  }

  if (m>=0) {
    $('#timer').html(m+':'+pad2(s));

    // pass the current values for m and s into startTimer
    setTimeout(function(){
        startTimer(m,s);
    }, 1000);
  } 
  else alert('time\'s up');
}

// shorter version of your checkSecond function
function pad2(number) {
  return (number < 10 ? '0' : '') + number; 
}

检查小提琴:https://jsfiddle.net/j3txcjmz/