我找到了一个计算秒和分钟的脚本。当我点击一个停止按钮时,我想获得分钟和秒值并将其存储在一个变量中,我应该怎么做?
var initialTime = Date.now();
window.setInterval(checkTime, 100);
function checkTime( miliseconds) {
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
if(seconds > 30 || minutes > 0) {
$('#timer').html('<span style="color: red">' + minutes + ': ' + seconds + '</span>');
} else {
$('#timer').html('<span style="color: black">' + minutes + ': ' + seconds + '</span>');
}
}
function convertTime(miliseconds) {
totalSeconds = Math.floor(miliseconds/1000);
minutes = Math.floor(totalSeconds/60);
seconds = totalSeconds - minutes * 60;
return minutes,seconds;
}
答案 0 :(得分:0)
您可以像这样从函数返回值:
<强> HTML 强>
<button id="stop">Stop</button>
<button id="start" disabled>Start</button>
<div id="timer"></div>
<div id="output"></div>
<强>的JavaScript 强>
var initialTime = Date.now();
var timer = window.setInterval(checkTime, 100);
function checkTime() {
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
if(formatted.seconds > 30 || formatted.minutes > 0) {
$('#timer').html('<span style="color: red">' + formatted.minutes + ': ' + formatted.seconds + '</span>');
} else {
$('#timer').html('<span style="color: black">' + formatted.minutes + ': ' + formatted.seconds + '</span>');
}
return formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return {'seconds': seconds,'minutes':minutes};
}
function toggle() {
$('#start, #stop').prop('disabled', function(i, v) { return !v; });
}
$('#stop').on('click',function() {
clearInterval(timer);
toggle();
var t = checkTime();
$('#output').html('Time was stopped at: '+t.minutes + ':' + t.seconds)
})
$('#start').on('click',function() {
initialTime = Date.now();
timer = window.setInterval(checkTime, 100);
toggle();
})
您可以在此处看到它:https://jsfiddle.net/jqy0ehbp/3/
答案 1 :(得分:0)
制作一个按钮并在其上附加活动。然后清除单击按钮时的间隔:
$("button").on('click', function() {
window.clearInterval(interval);
});
演示:https://jsfiddle.net/76t086c2/
您可以从div#timer
获取值,也可以在输入中设置分钟/秒,单击按钮时,获取值。
答案 2 :(得分:0)
好的,你有两个约会。
获得毫秒差异并格式化结果。
var initialTime = new Date(2016, 2, 09, 10, 00, 0);
var now = new Date(Date.now());
var dateDifference = (now - initialTime);
console.log('Diff miliseconds = ', dateDifference);
console.log('Result: ', FormatMiliseconds(dateDifference));
你可以在这个小提琴中查看一个例子: