当时间<= 0时停止计时功能

时间:2019-01-09 17:20:26

标签: javascript function timer

我正在尝试创建一个自动从0停止的计时器。现在,我可以使用按钮启动和停止计时器,但是我试图在游戏中实现计时器功能,因此它需要在0处停止。

let x;
let time = 15;
// let x = setTimeout(function(){ timer(); }, 1000);

let timer = function() {
    x = setInterval(function() {
        time -= 1
        document.getElementById("timer").innerHTML = time + " seconds";
    }, 1000)
}

let stopTimer = function() {
    clearTimeout(x)
}



$("#start").click(function(){
 	timer()
 })

$("#stop").click(function(){
 	stopTimer()
 })
<!DOCTYPE html>
<html>
<head>
	<title>Timer</title>
</head>
<body>
	<h1>Timer</h1>
	<p id="timer"></span></p>
	<h2><button id="start">Start Timer</button></h2>
	<h3><button id="stop">Stop Timer</button></h3>

	
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="app2.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

我添加了

if(time == 0){
    stopTimer();
 }

检查它何时到达0,然后调用stop:)

let x;
let time = 15;
// let x = setTimeout(function(){ timer(); }, 1000);

let timer = function() {
    x = setInterval(function() {
        time -= 1
        document.getElementById("timer").innerHTML = time + " seconds";
        if(time == 0){
            stopTimer();
          }
    }, 1000)
}

let stopTimer = function() {
    clearTimeout(x)
}



$("#start").click(function(){
 	timer()
 })

$("#stop").click(function(){
 	stopTimer()
 })
<!DOCTYPE html>
<html>
<head>
	<title>Timer</title>
</head>
<body>
	<h1>Timer</h1>
	<p id="timer"></span></p>
	<h2><button id="start">Start Timer</button></h2>
	<h3><button id="stop">Stop Timer</button></h3>

	
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="app2.js"></script>
</body>
</html>

答案 1 :(得分:0)

查看clearInterval,这是一种停止已启动的setInterval的方法。请在下面查看我的示例的编辑版本。

let x;
let time = 15;
// let x = setTimeout(function(){ timer(); }, 1000);

let timer = function() {
    x = setInterval(function() {
        time -= 1
        document.getElementById("timer").innerHTML = time + " seconds";
        if (time == 0) {
            stopTimer();
        }
    }, 1000)
}

let stopTimer = function() {
    clearInterval(x)
}



$("#start").click(function(){
 	timer()
 })

$("#stop").click(function(){
 	stopTimer()
 })
<!DOCTYPE html>
<html>
<head>
	<title>Timer</title>
</head>
<body>
	<h1>Timer</h1>
	<p id="timer"></span></p>
	<h2><button id="start">Start Timer</button></h2>
	<h3><button id="stop">Stop Timer</button></h3>

	
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="app2.js"></script>
</body>
</html>