Home > Mobile >  countdown timer stop (how to do in this situation)
countdown timer stop (how to do in this situation)

Time:08-18

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?

function goTime(){
 // in thist funcion we change color of button on click,also it will help me stop timer
  let color = $('#time').css('background-color');
  
  if (color=='rgb(0, 0, 0)'){
    $('#time').css('background-color','grey');
    let colors = setInterval(timer, 1000); 
    //start countdown timer
  }
  
  if(color=='rgb(128, 128, 128)'){ 
    $('#time').css('background-color','black');
  }

}

//this funcion starts every 1 second
function timer() {
    var elem = document.getElementById('time');
  let color = $('#time').css('background-color'); 
  if (color=='rgb(128, 128, 128)'){
  elem.innerText --;
  }
}
#time{
  margin-top:15px;
  background: black; 
  color:white;
  padding: 6px; 
  width: 123px; 
  height: auto;
  margin-left:-3px;

  text-align: center;
  font-family: Open Sans;
  font-style: normal;
  font-weight: bold;
  font-size: 65px;
  line-height: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <p id="time" onclick="goTime()">90</p>

CodePudding user response:

Clear the interval in your JavaScript file as follows every time in the goTime function:

var colors;

function goTime(){
  clearInterval(colors)
 // in thist funcion we change color of button on click,also it will help me stop timer
  let color = $('#time').css('background-color');
  
  if (color=='rgb(0, 0, 0)'){
    $('#time').css('background-color','grey');
    colors = setInterval(timer, 1000); 
    //start countdown timer
  }
  
  if(color=='rgb(128, 128, 128)'){ 
    $('#time').css('background-color','black');
  }

}

//this funcion starts every 1 second
function timer() {
    var elem = document.getElementById('time');
  let color = $('#time').css('background-color'); 
  if (color=='rgb(128, 128, 128)'){
  elem.innerText --;
  }
}
  • Related