skip to Main Content

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


  1. In your function to remove the script call the clearInterval function before removing the script from the page – as:

    function DeleteScript() {
      if( !isNaN(intervalId) )clearInterval( intervalId );
      document.scripts.flexiblesource.remove();
      console.log('#ok#')
    }
    <button onclick="StartTimer();">Start Timer</button>
    <button onclick="DeleteScript();">Stop Timer</button>
    
    <script id='flexiblesource'>
      var intervalId;
      var i=1;
    
      function DoThis() {
        console.clear();
        console.log(`Doing it...${i}`);
        i++;
      }
    
      function StartTimer() {
        intervalId = window.setInterval(
          function() {
            DoThis();
          }, 1000);
      }
    </script>
    Login or Signup to reply.
  2. Rather than removing the script, use clearInterval() function. it will stop the setInterval() function.

    Please refer the clearInterval() function Here.

    <html>
    <body>
    <button onclick="StartTimer();" >Start Timer</button>
    <button onclick="DeleteScript();" >Stop Timer</button>
    <script>
             var intervalId;
             function DeleteScript()
             {
                window.clearInterval(intervalId);
             }
    
            function DoThis()
            {
                console.log("Doing it...");
            }
    
            function StartTimer()
            {
                 intervalId = window.setInterval(
                    function()
                    {
                        DoThis();
                    }
                    , 1000);
            }
            
    </script>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search