I have a simple HTML code with two buttons. When one button is pressed, a timer is started. This timer is located in a script that normally would be retreived with JQuery.
Then we have another button, that would delete (clear) the script. Unfortunaly the timer remains resident. I do receive an error when i try to delete the script twice, but i can start multiple timers even when the script was removed.
<html>
<body>
<button onclick="StartTimer();" >Start Timer</button>
<button onclick="DeleteScript();" >Stop Timer</button>
<script>
function DeleteScript()
{
document.scripts.flexiblesource.remove();
}
</script>
<script id="flexiblesource">
var intervalId;
function DoThis()
{
console.log("Doing it...");
}
function StartTimer()
{
intervalId = window.setInterval(
function()
{
DoThis();
}
, 1000);
}
</script>
</body>
</html>
I was expecting the timers also to be "destroyed".
2
Answers
In your function to remove the script call the
clearInterval
function before removing the script from the page – as:Rather than removing the script, use
clearInterval()
function. it will stop thesetInterval()
function.Please refer the
clearInterval()
function Here.