【问题标题】:clearTimeout() not clearing timerclearTimeout() 不清除定时器
【发布时间】:2017-06-24 03:13:21
【问题描述】:
function countDown(secs,elem)
{   
    var element = document.getElementById(elem);
    element.innerHTML = "Game ends in " + secs + " seconds!";
    if(secs<1)
    {   
        clearTimeout(timer);
        document.getElementById('gameContent').style.display='none';

    }
    secs--;
    var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);

}

 <div class="timerCount" id="status"></div>
 <script>countDown(5,"status");</script>

我的计时器在 5 秒后正确启动并递减。我的游戏 div 在计时器达到 0 后隐藏,但计时器没有清除并结束,而是变为负数。请我的代码中的错误,以便停止计时器并清除它

【问题讨论】:

  • clearTimeout(timer); timer 每次都为空。您将 timer 声明为函数中的最后一个变量 - 您如何期望它被事先访问?
  • countDown 方法之外声明timer。它需要在方法调用之间持续存在。

标签: javascript html css cleartimeout


【解决方案1】:

如果您只使用setInterval 并执行以下操作会更有效:

function countDown(secs, elem) {
  var interval;
  var element = document.getElementById(elem);
  var timer = setInterval(function() {
    secs--;
    update();
    if (secs < 1) {
      clearInterval(timer);
    }
  }, 1000);

  function update() {
    if (secs > 0) {
      element.innerHTML = "Game ends in " + secs + " seconds!";
    } else {
      document.getElementById('gameContent').style.display = 'none';
    }
  }
  update();

}

countDown(5, "status");
<div id="gameContent">
  <h1>Game</h1>
  <div class="timerCount" id="status"></div>
</div>

【讨论】:

    【解决方案2】:

    清除超时没有任何意义,因为您处于要清除的超时调用的回调中,所以确实没有什么要清除的。即使您将timer 声明为全局变量,这仍然无法解决这个概念问题。

    您的问题确实是在您的秒数用完后您仍然调用setTimeout。所以,在这样做之前退出函数(或使用else):

    function countDown(secs,elem)
    {   
        var element = document.getElementById(elem);
        element.innerHTML = "Game ends in " + secs + " seconds!";
        if(secs<1)
        {   
            document.getElementById('gameContent').style.display='none';
            return; // <-------- add this!
        }
        secs--;
        // avoid passing string as first argument to setTimeout:
        setTimeout(countDown.bind(null, secs, elem),1000);
    }
    

    注意:将字符串作为第一个参数传递给setTimeout 被认为是不好的做法:需要评估该字符串,就像eval 一样。除了程序员对eval 的保留之外,在这种情况下它也效率较低且没有必要。

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2021-09-23
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多