Reputation: 47
I made a simple timer, the problem is i can't stop it by clicking on 'stop' button. Also i found out that if click start button multiple times, the timer would speed up, is there any method to fix it? And how do i manually pass the desired amount of time(by putting it into the prompt)after stopping the timer or after the time has expired?
let getId = x => document.getElementById(x);
let total = 20;
function check(x) {
if(x<10){
x= "0"+x;
return x;
}
else return x;
}
let hours = Math.floor(total / 3600);
let minutes = Math.floor(total % 3600 / 60);
let seconds = Math.floor(total % 3600 % 60);
hours = check(hours);
minutes = check(minutes);
seconds = check(seconds);
getId('timer').innerHTML = hours + ':' + minutes + ':' +seconds;
function start() {
let hours = Math.floor(total / 3600);
let minutes = Math.floor(total % 3600 / 60);
let seconds = Math.floor(total % 3600 % 60);
hours = check(hours);
minutes = check(minutes);
seconds = check(seconds);
getId('timer').innerHTML = hours + ':' + minutes + ':' +seconds;
if(total == 0){
getId('timer').innerHTML+= '<br>' + 'Time expired';
return;
}
total--;
}
getId('set').addEventListener('click', function(){
let total = +prompt('Insert desired countdown');
});
getId('start').addEventListener('click', function(){
let timer = setInterval(start,1000);
if(total == 0){
clearInterval(timer);
}
});
getId('stop').addEventListener('click', function(){
clearInterval(timer);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<p id="timer"></p>
<form action="">
<input type="button" id="set" value="Set">
<input type="button" id="start" value="Start">
<input type="button" id="stop" value="Stop">
</form>
<script src="script.js"></script>
</body>
</html>
Upvotes: 1
Views: 583
Reputation: 2010
timer
variable is declarated inside anonymous function. So it is only available inside that function.
You need to move let timer
outside. Like below.
let timer;
getId('start').addEventListener('click', function(){
timer = setInterval(start,1000);
if(total == 0){
clearInterval(timer);
}
});
getId('stop').addEventListener('click', function(){
clearInterval(timer);
});
here is codepen with timer set working, and preventing speeding up. Few things are missing (for example you should check if input value is a number), but it is working.
Upvotes: 1
Reputation: 1581
Your timer variable is local to start method that's why stop is not working (make it global). Additionally in start method first check if timer is set and clear it if it is, to avoid speeding up.
Upvotes: 0