Search code examples
javascripttimercountdown

countdown timer stop not working


I am using a countdown timer in my page which is working fine . i tried to make code for stop button but the logic doesnt seems to be working here is my code

$('.Stop').click('click', function() {
  clearTimeout( myTimer);
});

function calltimer() {
  countdown( "countdown", 1, 5 );
}


function countdown( elementName, minutes, seconds ) {
  var element, endTime, hours, mins, msLeft, time,myTimer ;

  function twoDigits( n ) {
      return (n <= 9 ? "0" + n : n);
  }

  function updateTimer() {
      msLeft = endTime - (+new Date);
      if ( msLeft < 1000 ) {
          element.innerHTML = "countdown's over!";
      } else {
          time = new Date( msLeft );
          hours = time.getUTCHours();
          mins = time.getUTCMinutes();
          element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
          myTimer =setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
      }
  }

  element = document.getElementById( elementName );
  endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
  updateTimer();
}

i tried setInterval which is not seems to be work

$('.Stop').click('click', function() {
    setInterval(updateWCTime, 1000);
});

and this code

$('.Stop').click('click', function() {
  clearTimeout( updateTimer);
});

Need some suggestion , thanks


Solution

  • This is how to use clearTimeout.

    var timeout = setTimeout(function() { console.log("Hi!"); }, 5000);
    clearTimeout(timeout);
    

    About your countdown timer, I think you should use setInterval and clearInterval instead.