我怎么能在javascript中停止计时器?

时间:2016-12-23 10:20:04

标签: javascript

我希望当用户点击提交计时器停止时 当我添加 clearInterval 我有错误

我的代码:

  <html>
  <body>
  <button onclick="myStopFunction()">submit</button>
<div><span id="time">01:00</span> minutes!</div>
<script type="text/javascript">



    function startTimer(duration, display) {
        var timer = duration,
            minutes, seconds;
                 var handle = setInterval(function() {
            minutes = parseInt(timer / 60, 10) //10 the ten system 
            seconds = parseInt(timer % 60, 10);
            display.textContent = minutes + ":" + seconds;


    }   

    function myStopFunction() {
clearInterval(myVar);
}

3 个答案:

答案 0 :(得分:2)

你应该在startTimer范围之外使用intervalHandle。优良作法是创建闭包(如下所示),以便不使用不需要公开的变量来规范全局范围。

请记得致电startTimer。

您可以使用以下解决方案:

<html>
<body>
<button onclick="myStopFunction()">submit</button>
<div><span id="time">01:00</span> minutes!</div>
<script type="text/javascript">
    (function() { //create closure to not polute global scope
        var intervalHandle;

        function startTimer(duration, display) {
            var timer = duration,
                    minutes, seconds;

            //assign interval handle to outer scope
            intervalHandle = setInterval(function() {
                minutes = parseInt(timer / 60, 10); //10 the ten system
                seconds = parseInt(timer % 60, 10);
                display.textContent = minutes + ":" + seconds;
            }, timer);
        }

        function myStopFunction() {
            clearInterval(intervalHandle);
        }

        // export functions to global scope
        window.startTimer = startTimer;
        window.myStopFunction = myStopFunction;
    })();
</script>
</body>
</html>

快乐的黑客攻击!

答案 1 :(得分:1)

包含handle函数的var setInterval仅存在于其范围内:函数startTimer。 因此,只需在函数中声明var handle;,然后在stop函数中调用clearInterval(handle); (显然在代码中保留handle = setInterval(function() {...})。

答案 2 :(得分:1)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button type="button" onclick="start()">Start</button>
<button type="button" onclick="stop()">Stop</button>
<p id="test">

</p>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>


</body>
</html>




  var count = 0;
var myVar;
  function start() {
    myVar = setInterval(function() {
      console.log('hi');
      $('#test').text('hi' + count++);
    }, 1000);
    return myVar;
  }


  function stop() {
    clearInterval(myVar);
  }