故障排除停止倒计时器

huangapple go评论82阅读模式
英文:

Troubleshooting stopping a countdown timer

问题

我创建了一个简单的倒计时器,用于显示45秒的倒计时。我尝试使用JavaScript的onclick函数来通过两个按钮来控制这个计时器。一个按钮将启动计时器,另一个将停止计时器。我能够启动计时器并在屏幕上显示它,但无法停止它。我在网上找到了这个时间脚本并修改它,以仅显示秒数。

我尝试创建一个全局变量(在这种情况下是"var xx;")来清除间隔,但没有成功。我不确定缺少什么。以下是我使用Bootstrap 4的代码的重要部分:

<!-- 创建一个全局变量以便稍后重置间隔 -->
var xx;

// 可见倒计时45秒函数
function VisibleCountDownTimer45s() {

    // 如果已经定义了xx,则重置间隔
    if (xx != undefined) {
        clearInterval(xx);
    };

    // 设置我们要倒计时的日期
    var countDownDate = new Date().getTime() + 45000;

    // 每1秒更新一次倒计时
    xx = setInterval(function () {
        // 获取当前的日期和时间
        var now = new Date().getTime();

        // 计算现在和倒计时日期之间的距离
        var distance = countDownDate - now;

        // 计算剩余秒数
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // 在id为"demo"的元素中显示结果
        document.getElementById("demo").innerHTML = seconds + "s ";

        // 如果倒计时结束,写一些文本
        if (distance < 0) {
            clearInterval(xx);
            document.getElementById("demo").innerHTML = "";
        }
    }, 1000);
}
<!-- 计时器显示框 -->
<div class="container">
    <div class="row mb-3">
        <div class="col-md-4">&nbsp;</div>
        <div class="col-md-4 text-center pb-3" id="demo"><span class="border border-secondary p-2">显示计时器</span></div>
        <div class="col-md-4">&nbsp;</div>
    </div>
</div>

<!-- 控制按钮 -->
<div class="container">
    <div class="row">
        <div class="col-md-4 text-right"><button class="btn btn-primary" onclick="VisibleCountDownTimer45s()">启动可见计时器</button></div>
        <div class="col-md-4 text-center" id="Counter"><p>&nbsp;</p></div>
        <div class="col-md-4 text-left"><button class="btn btn-primary" onclick="clearInterval(xx)">停止可见计时器</button></div>
    </div>
</div>

请注意,在停止计时器的按钮中,我们使用了clearInterval(xx)来清除间隔。希望这对你有所帮助。

英文:

I created a simple countdown timer to display a count down of 45 seconds. I am trying to control this timer by two buttons using the JavaScript onclick function. One button will start the timer and one will stop it. I am able to start the time and get it to display on screen, but not able to stop it. I found the time script online and modified it to show only the seconds.

I tried to create a global id ("var xx;" in this case) to clear the interval but did not work. I am not sure what is missing. Here is the important parts of my code using Bootstrap 4.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// create a global variable to reset the interval later
var xx;

// Visible Coundown 45s function
function VisibleCountDownTimer45s() {

// reset internval if it is already in defined.
if(xx != undefined) {
clearInterval(xx)
};

// Set the date we&#39;re counting down to
   var countDownDate = new Date().getTime() + 45000;
// Update the count down every 1 second
   var xx = setInterval(function() {
// Get today&#39;s date and time
   var now = new Date().getTime();
// Find the distance between now and the count down date
   var distance = countDownDate - now;
// console.log (distance);
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id=&quot;demo&quot;
        document.getElementById(&quot;demo&quot;).innerHTML =  seconds + &quot;s &quot;;
// If the count down is finished, write some text
        if (distance &lt; 0) {
            clearInterval(xx);
            document.getElementById(&quot;demo&quot;).innerHTML = &quot;&quot;;
          }
        }, 1000);
    }	 

<!-- language: lang-html -->

&lt;!-- timer display box --&gt;

&lt;div class=&quot;container&quot;&gt;
&lt;div class=&quot;row mb-3&quot;&gt;
&lt;div class=&quot;col-md-4&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;col-md-4 text-center pb-3&quot; id=&quot;demo&quot;&gt;&lt;span class=&quot;border border-secondary p-2&quot;&gt;show     timer here&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;col-md4&quot;&gt;&amp;nbsp;&lt;/div&gt;	
&lt;/div&gt;
&lt;/div&gt;

&lt;!-- control buttons --&gt;

&lt;div class=&quot;container&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-4 text-right&quot;&gt;&lt;button class=&quot;btn btn-primary&quot; onclick=&quot;VisibleCountDownTimer45s()&quot;&gt;Start visible Timer&lt;/button&gt;&lt;/div&gt;
&lt;div class=&quot;col-md-4 text-center&quot; id=&quot;Counter&quot;&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;/div&gt;
&lt;div class=&quot;col-md4 text-left&quot;&gt;&lt;button class=&quot;btn btn-primary&quot; onclick=&quot;clearInterval(xx)&quot;&gt;Stop visible Timer&lt;/button&gt;&lt;/div&gt;	
&lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

在你的 VisibleCountDownTimer45s() 函数内部的问题在于,你重新声明了一个局部作用域变量 xx。移除那里的 var 关键字,你将会把计时器分配给全局的 xx 变量,这样其他函数就能够访问它。这被称为作用域问题。

将这个改变:

从:var xx = setInterval(function() {

到:xx = setInterval(function() {

请参考以下代码示例:

// 创建一个全局变量以便以后重置间隔
var xx;

// 可见倒计时 45 秒的函数
function VisibleCountDownTimer45s() {

  // 如果已经定义了 xx,重置间隔
  if (xx != undefined) {
    clearInterval(xx)
  };

  // 设置我们要倒计时的日期
  var countDownDate = new Date().getTime() + 45000;
  
  // 每秒更新一次倒计时
  xx = setInterval(function() {
    // 获取当前日期和时间
    var now = new Date().getTime();
    // 计算现在和倒计时日期之间的距离
    var distance = countDownDate - now;
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    // 在具有 id="demo" 的元素中显示结果
    document.getElementById("demo").innerHTML = seconds + "s ";
    // 如果倒计时结束,写一些文本
    if (distance < 0) {
      clearInterval(xx);
      document.getElementById("demo").innerHTML = "";
    }
  }, 1000);
}

此外值得注意的是,你可以在不使用 Date 对象且不计算相对于它的经过时间的情况下实现相同的结果。

以下是一个示例代码:

let timer;

function startTimer(interval) {
  if (timer !== undefined) {
    clearInterval(timer);
  };
  timer = setInterval(function() {
    interval -= 1000
    if (interval <= 0) {
      clearInterval(timer);
      document.getElementById("demo").innerHTML = "";
    } else {
      const seconds = Math.floor(interval / 1000);
      document.getElementById("demo").innerHTML = seconds + "s ";
    }
  }, 1000);
}
英文:

Your problem is that inside of your VisibleCountDownTimer45s() function, you are redeclaring a locally-scoped variable named xx. Remove the var keyword there, and you'll be assigning the timer to the global xx variable that is accessible to other functions. This is known as a scope issue.

Change: var xx = setInterval(function() {

To: xx = setInterval(function() {

See this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// create a global variable to reset the interval later
var xx;

// Visible Coundown 45s function
function VisibleCountDownTimer45s() {

  // reset internval if it is already in defined.
  if (xx != undefined) {
    clearInterval(xx)
  };

  // Set the date we&#39;re counting down to
  var countDownDate = new Date().getTime() + 45000;
  // Update the count down every 1 second
  xx = setInterval(function() {
    // Get today&#39;s date and time
    var now = new Date().getTime();
    // Find the distance between now and the count down date
    var distance = countDownDate - now;
    // console.log (distance);
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    // Display the result in the element with id=&quot;demo&quot;
    document.getElementById(&quot;demo&quot;).innerHTML = seconds + &quot;s &quot;;
    // If the count down is finished, write some text
    if (distance &lt; 0) {
      clearInterval(xx);
      document.getElementById(&quot;demo&quot;).innerHTML = &quot;&quot;;
    }
  }, 1000);
}

<!-- language: lang-html -->

&lt;div class=&quot;container&quot;&gt;
  &lt;div class=&quot;row mb-3&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;&amp;nbsp;&lt;/div&gt;
    &lt;div class=&quot;col-md-4 text-center pb-3&quot; id=&quot;demo&quot;&gt;&lt;span class=&quot;border border-secondary p-2&quot;&gt;show     timer here&lt;/span&gt;&lt;/div&gt;
    &lt;div class=&quot;col-md4&quot;&gt;&amp;nbsp;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot;&gt;
  &lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-4 text-right&quot;&gt;&lt;button class=&quot;btn btn-primary&quot; onclick=&quot;VisibleCountDownTimer45s()&quot;&gt;Start visible Timer&lt;/button&gt;&lt;/div&gt;
    &lt;div class=&quot;col-md-4 text-center&quot; id=&quot;Counter&quot;&gt;
      &lt;p&gt;&amp;nbsp;&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;col-md4 text-left&quot;&gt;&lt;button class=&quot;btn btn-primary&quot; onclick=&quot;clearInterval(xx)&quot;&gt;Stop visible Timer&lt;/button&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

Also worth noting that you can achieve the same result without using a Date object and calculating the elapsed time relative to it.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let timer;

function startTimer(interval) {
  if (timer !== undefined) {
    clearInterval(timer);
  };
  timer = setInterval(function() {
    interval -= 1000
    if (interval &lt;= 0) {
      clearInterval(timer);
      document.getElementById(&quot;demo&quot;).innerHTML = &quot;&quot;;
    } else {
      const seconds = Math.floor(interval / 1000);
      document.getElementById(&quot;demo&quot;).innerHTML = seconds + &quot;s &quot;;
    }
  }, 1000);
}

<!-- language: lang-html -->

&lt;div class=&quot;container&quot;&gt;
  &lt;div class=&quot;row mb-3&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;&amp;nbsp;&lt;/div&gt;
    &lt;div class=&quot;col-md-4 text-center pb-3&quot; id=&quot;demo&quot;&gt;&lt;span class=&quot;border border-secondary p-2&quot;&gt;show     timer here&lt;/span&gt;&lt;/div&gt;
    &lt;div class=&quot;col-md4&quot;&gt;&amp;nbsp;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;container&quot;&gt;
  &lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-4 text-right&quot;&gt;&lt;button class=&quot;btn btn-primary&quot; onclick=&quot;startTimer(45000)&quot;&gt;Start visible Timer&lt;/button&gt;&lt;/div&gt;
    &lt;div class=&quot;col-md-4 text-center&quot; id=&quot;Counter&quot;&gt;
      &lt;p&gt;&amp;nbsp;&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;col-md4 text-left&quot;&gt;&lt;button class=&quot;btn btn-primary&quot; onclick=&quot;clearInterval(timer)&quot;&gt;Stop visible Timer&lt;/button&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月6日 02:22:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59602910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定