简体   繁体   中英

Why does clearInterval works only once?

I have this example:

<p id="test"></p>

<button onClick="clearInterval(myVar)">Stop time!</button>
<button onClick="setInterval(myTimer, 1000)">Start time!</button>

<script>

var myVar = setInterval(myTimer, 1000);

function myTimer() {
    var d = new Date();
    document.getElementById('test').innerHTML = d.toLocaleTimeString();
}

</script>

When I click "Stop time!" for the first time it works as it should, but after I click "Start time!" I cannot stop timer anymore. Why exactly is this happening and how to fix this?

Thanks.

Look at this code

<button onClick="setInterval(myTimer, 1000)">Start time!</button>

It does not work because you do not set the new timer to the variable. It does not know the new value should be set there.

Not a fan of inline code, but this would work

<button onClick="myVar = setInterval(myTimer, 1000)">Start time!</button>

A better design would be something like this:

 (function() { var timer; function myTimer() { var d = new Date(); document.getElementById('test').innerHTML = d.toLocaleTimeString(); } function startTimer() { stopTimer(); //make sure timer is not already running timer = setInterval(myTimer, 1000); //start new timer } function stopTimer() { if (timer) clearInterval(timer); timer = null; } document.getElementById("stop").addEventListener("click", stopTimer); document.getElementById("start").addEventListener("click", startTimer); startTimer(); }()); 
 <p id="test"></p> <button id="stop">Stop time!</button> <button id="start">Start time!</button> 

Try this..

<p id="test"></p>

<button onClick="clearInterval(myVar)">Stop time!</button>
<button onClick="startTimer()">Start time!</button>
<script>
var myVar;

function startTimer() {

    myVar = setInterval(myTimer, 1000);
}

function myTimer() {
    var d = new Date();
    document.getElementById('test').innerHTML = d.toLocaleTimeString();
}
</script>

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