i am learning setTimeout, setInterval, clearInterval functions. now i tried to write such code, but clearInterval is not working. Code:
<h2>Hello!</h2>
<p>i am a paragraph</p>
<button onclick="setInterval(messageOnInterval, 110)">Click Me</button>
<button onclick="clearInterval(messageOnInterval)">Stop</button>
<script>
function messageOnInterval() {
var p=document.createElement('p');
p.innerHTML = "i am a paragraph";
document.body.appendChild(p);
}
</script>
Thank you in advance for help!
CodePudding user response:
You should assign setInterval
to a variable to get it's handle which is in number format, then you can call clearInterval
to clear that timer.
You cannot assign a function to clearInterval
.
So it should be like this:
<script>
function messageOnInterval_Impl() {
var p = document.createElement('p');
p.innerHTML = "i am a paragraph";
document.body.appendChild(p);
}
var intervalHandle;
function setMessageOnInterval() {
intervalHandle = setInterval(function () {
messageOnInterval_Impl();
// ...
}, 110)
}
</script>
<h2>Hello!</h2>
<p>i am a paragraph</p>
<button onclick="setMessageOnInterval()">Click Me</button>
<button onclick="clearInterval(intervalHandle)">Stop</button>
CodePudding user response:
setInterval
returns a value that needs to be used when calling clearInterval
. You don't pass the function as arg, but the value returned by an earlier call to setInterval
id = setInterval(messageOnInterval, 110)
clearInterval(id)
In your case you should declare a JS variable inside a script
and use that as your id.
Note: this will not properly work if you press the button multiple times, as you'll lose older setInteval
returned values.