i try to do countdown timer. But i get a double timer on the third click,and the more and more after next click… I am racking my brain trying to figure how do this. Can you help me?
JavaScript
x
24
24
1
function goTime(){
2
// in thist funcion we change color of button on click,also it will help me stop timer
3
let color = $('#time').css('background-color');
4
5
if (color=='rgb(0, 0, 0)'){
6
$('#time').css('background-color','grey');
7
let colors = setInterval(timer, 1000);
8
//start countdown timer
9
}
10
11
if(color=='rgb(128, 128, 128)'){
12
$('#time').css('background-color','black');
13
}
14
15
}
16
17
//this funcion starts every 1 second
18
function timer() {
19
var elem = document.getElementById('time');
20
let color = $('#time').css('background-color');
21
if (color=='rgb(128, 128, 128)'){
22
elem.innerText --;
23
}
24
}
JavaScript
1
16
16
1
#time{
2
margin-top:15px;
3
background: black;
4
color:white;
5
padding: 6px;
6
width: 123px;
7
height: auto;
8
margin-left:-3px;
9
10
text-align: center;
11
font-family: Open Sans;
12
font-style: normal;
13
font-weight: bold;
14
font-size: 65px;
15
line-height: 80px;
16
}
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<p id="time" onclick="goTime()">90</p>
Advertisement
Answer
Clear the interval in your JavaScript file as follows every time in the goTime function:
JavaScript
1
28
28
1
var colors;
2
3
function goTime(){
4
clearInterval(colors)
5
// in thist funcion we change color of button on click,also it will help me stop timer
6
let color = $('#time').css('background-color');
7
8
if (color=='rgb(0, 0, 0)'){
9
$('#time').css('background-color','grey');
10
colors = setInterval(timer, 1000);
11
//start countdown timer
12
}
13
14
if(color=='rgb(128, 128, 128)'){
15
$('#time').css('background-color','black');
16
}
17
18
}
19
20
//this funcion starts every 1 second
21
function timer() {
22
var elem = document.getElementById('time');
23
let color = $('#time').css('background-color');
24
if (color=='rgb(128, 128, 128)'){
25
elem.innerText --;
26
}
27
}
28