倒数计时器停止不工作

countdown timer stop not working

我在我的页面中使用倒数计时器,它工作正常。我试图为停止按钮编写代码,但逻辑似乎不起作用 这是我的代码

$('.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();
}

我尝试了 setInterval,但似乎不起作用

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

和这段代码

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

需要一些建议,谢谢

这是clearTimeout的使用方法。

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

关于你的倒数计时器,我认为你应该使用 setIntervalclearInterval 来代替。

myTimerupdateTimer() 函数的 local 变量。它在点击处理程序范围内未定义。因此,您可以改用全局变量,请参阅下面的可运行示例。

var myTimer;

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

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

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

  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();
}

countdown("counter", 1, 30);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"></p>
<button class="Stop" type="button">Stop</button>