首页 > 解决方案 > 无法清除设置间隔功能

问题描述

我正在为计时器创建设置间隔功能。我成功实现了设置间隔功能。

我需要使用清除间隔功能停止计时器。我编写了 stop_timer 函数来停止,但我无法停止计时器。

我通过在全局中声明空变量来尝试它。我无法得到。以下是我尝试过的代码。

HTML 代码:

<div id="t_demo"></div>
<button onclick="clear_timer()">clear</button>

Javascript代码:

var x = "";

function start_timer() {
  // Update the count down every 1 second
  var x = setInterval(function() {
    var countDownDate = new Date("2019-09-25 05:05:05");
    // Get todays date and time
    var now = new Date().getTime();


    // Find the distance between now an the count down date
    var distance = now - countDownDate;



    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("t_demo").innerHTML = hours + ":" + minutes + ":" + seconds;

  }, 1000);

}

start_timer();

function clear_timer() {
  clearInterval(x);
}

标签: javascripttimer

解决方案


You are assigning the interval to a new variable.

Try changing the line

var x = setInterval(function() {

To

x = setInterval(function() {

推荐阅读