简体   繁体   中英

Trying to stop Interval on a function

I'm trying to create a button that on click will start a timer and on second click will stop it and change the innerHtml of "button" to the time where you stopped the timer. However it doesn't work with the code I've written below, the Interval just keeps going and it seem's like its creating multiple ones with each click.

Any ideas why?

var active = false;
var sec = 0;
function clock(){
    if(active === false) {
        var clock = setInterval("timer()", 1000);
        active = true;
    }
    else if(active === true){
        clearInterval(clock);
        document.getElementById("button").innerHTML = "You clicked at "+sec+" seconds, try again.";
        active = false;
        sec = 0;
    }
}
function timer() {
    sec++;
    document.getElementById("button").innerHTML = sec;
}

You don't have the same context for var clock; every time your button is clicked, the last context of this variable is lost for the next click, so make it global just like you did with var active; and rename differently from your function name just to avoid troubles:

js

var active = false;
var sec = 0, clck;

function clock() {
    if (active === false) {
        clck = setInterval("timer()", 1000);
        active = true;
    } else if (active === true) {
        clearInterval(clck);
        document.getElementById("button").innerHTML = "You clicked at " + sec + " seconds, try again.";
        active = false;
        sec = 0;
    }
}

function timer() {
    sec++;
    document.getElementById("button").innerHTML = sec;
}

html

<button id="button" onclick="clock()">Start Timer</button>

fiddle

You miss out click event handlers and any example HTML so I have implemented what was missing and come up with this.

<!DOCTYPE html>
<html>
  <head>
   <script>
    var active = true;
    var sec = 0;
    var timer;

    function init() {
      var button = document.getElementById("button");

      button.addEventListener("click", function() {
        active = !active;

        if(active) {
          clearInterval(timer);
          button.innerHTML = "You clicked at " + sec + " seconds, try again!";  
          sec = 0;
        }

        else {
          timer = setInterval(function() {
            sec++;
            button.innerHTML = sec;
          }, 1000);
        }
      });
    }
  </script>
  </head>
  <body onload="init();">
    <span id="button">Start</span>
  </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM