Reputation: 101
I have a requirement where I need to call a function repeatedly which calls setInterval. The problem I encountered is, if a function is generated(say every 1second) and it is set using setInterval; if we call setInterval twice/more without a clearInterval in between the function keeps on calling itself. Ex :
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="myStartFunction()">Start time</button>
<button onclick="myStopFunction()">Stop time</button>
<script>
var myVar;
function myStartFunction(){
myVar = setInterval(function(){ myTimer() }, 1000);
}
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
console.log(myVar);
clearInterval(myVar);
console.log(myVar);
}
</script>
</body>
</html>
If I click the Start Time button twice without clicking Stop time in between, the function doesn't stop. This is just an example of the scenario. Anyway to resolve this?
Upvotes: 0
Views: 914
Reputation: 22923
You are overwriting the same myVar over and over again ... That means the stop function will only stop the last timer started. If you only want at most one setInteval to run, just add a call to the stop function before starting.
Upvotes: 0
Reputation: 78525
In your startFunction, just clear any existing intervals. Otherwise you are creating multiple intervals, but only storing a reference to the last interval created.
For example:
function myStartFunction(){
if(myVar) {
myStopFunction();
}
myVar = setInterval(function(){ myTimer() }, 1000);
}
Upvotes: 5