我正在尝试根据用户输入的MM:SS格式创建一个倒数计时器。因此,当用户输入10时,它将显示为10:00。但是我在逻辑上挣扎着如何减少时间格式中的数字。 即:10:00,9:59,9:58等
与我感到困惑的领域是,结构化和配置我的代码,以便当“分钟”减少1(即从10:00到9:59)时,经过60秒钟后它只会减少到8。 / p>
不幸的是,到目前为止,我只能以常规数字格式(例如10、9、8、7、6 ....)打印用户输入
HTML
<div class="form-group">
<label for="exampleFormControlInput1">Count down Timer</label>
<input type="number" class="form-control" id="timeInputForm" placeholder="Enter time in minutes">
</div>
<!-- submit button -->
<div class="text-center">
<button type="submit" class="btn btn-lg btn-success">Start</button>
</div>
JQUERY / JS
$('form').on('submit', function(e){
e.preventDefault();
userBreakMin = parseInt($('input#timeInputForm').val()); // retrieving user input and converting from string to int
let userBreakType = $('#formSelectOptions option:selected').text(); // grabbing the select option text
countDownTimer(userBreakMin);
});
const countDownTimer = (timeInMins) => {
let convertToMins = userBreakMin * 60;
let minutesInputed = convertToMins/60;
let seconds = 60; //parseInt(convertToMins%60);
setInterval(()=>{
minutesInputed -=1;
if(seconds >0){
--seconds;
};
// if(minutesInputed > 0 ){
// console.log(minutesInputed -=1);
// }
// if(seconds > 0 ){
// console.log(seconds -=1);
// }
},1000);
};
答案 0 :(得分:0)
您必须检查每次间隔迭代中秒是否为零...
Morevover,还必须查看它是否小于10,以便添加前导零。
最后,您必须检查clearInterval()的分钟和秒是否都为零。
这里是一个例子...
在代码中查找注释。 ;)
$('form').on('submit', function(e) {
e.preventDefault();
// Retrieve user input and convert to integer
userBreakMin = parseInt($('input#timeInputForm').val());
// Set the start time
$("#min").text(userBreakMin-1);
$("#sec").text("59");
// Call the function to start the interval.
countDownTimer(userBreakMin);
});
const countDownTimer = (timeInMins) => {
let convertToMins = userBreakMin * 60;
var myCountdown = setInterval(() => {
// Getting the displayed values
var minutes = parseInt($("#min").text());
var seconds = parseInt($("#sec").text());
// The end?
if(minutes == 0 && seconds == 0){
clearInterval(myCountdown);
}
else{
// If seconds are at 00, decrement the minutes
if (seconds == 0) {
seconds = 60;
$("#min").text(minutes-1);
}
// Decrement seconds
seconds--;
// Leading zero for seconds below 10
var leadingZero = "";
if(seconds<10){
leadingZero = "0";
}
$("#sec").text(leadingZero+seconds);
}
}, 1000);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="exampleFormControlInput1">Count down Timer</label>
<input type="number" class="form-control" id="timeInputForm" placeholder="Enter time in minutes">
</div>
<!-- submit button -->
<div class="text-center">
<button type="submit" class="btn btn-lg btn-success">Start</button>
</div>
</form>
<br>
<span id="min">0</span>:<span id="sec">00</span>