我可以阻止它但是如何让它在启动功能的当前时间再次启动?为什么这不起作用?
<!DOCTYPE>
<html>
<head>
</head>
<body>
<p id="demo"></p>
<button onclick="stopFunction()">Stop time</button>
<button onclick="startFunction()">Start time</button>
</body>
</html>
JavaScript的:
var myVar = setInterval(function () {
myTimer();
}, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function stopFunction() {
clearInterval(myVar);
}
function startFunction() {
document.getElementById("demo").innerHTML = t;
}
答案 0 :(得分:1)
将其更改为:
var t = d.toLocaleTimeString();
function myTimer()
{
var d;
d = new Date();
t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
var myVar = setInterval(myTimer, 1000);
function stopFunction()
{
clearInterval(myVar);
}
function startFunction()
{
document.getElementById("demo").innerHTML = t;
//Restart it here
myVar = setInterval(myTimer, 1000);
}
问题是你没有再次开始这段时间。现在就这样做了。
答案 1 :(得分:1)
编辑:我投入了一些代码,以便在运行时禁用启动按钮。这样做是个好主意,或者写下一些逻辑,以便每次点击/运行时都不会调用setInterval
<!DOCTYPE>
<html>
<head>
</head>
<body>
<p id="demo"></p>
<button id='stopButton' onclick="stopFunction()">Stop time</button>
<button id='startButton' onclick="startFunction()">Start time</button>
<script type='text/javascript'>
var myVar;
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function stopFunction() {
clearInterval(myVar);
document.getElementById("startButton").disabled = false;
}
function startFunction() {
myVar = setInterval(myTimer, 1000);
document.getElementById("startButton").disabled = true;
}
startFunction();
</script>
</body>
</html>