1

I've a script from a page tracker website, which do something periodically. Sometimes I need to re-run the script from scratch. To make this happen, I remove the script tag from DOM and append it again.

Since, the script uses setInterval the execution won't be finished when the script tag is removed.

What do you suggest for that?

Afshin
  • 977
  • 9
  • 16
  • You can override `setInterval`/`setTimeout` implementations *before* that script loads. See: https://stackoverflow.com/questions/858619/viewing-all-the-timeouts-intervals-in-javascript – nicholaswmin Oct 15 '19 at 08:49

2 Answers2

2

How about calling clearInterval ?
You'll need the handle to the interval, though.

var myVar = setInterval(myTimer, 1000);

function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
  clearInterval(myVar);
}

But if you can't or don't want to edit a 3rd party script, there is one thing you could do:

  • override the window.setInterval function.

like

var backup = window.setInterval;
var my_array = [];


window.setInterval = function(interval, function){
    var handle = backup(interval, function);
   my_array.push(handle);
   return handle;
}

then you can get all the handles from my_array, and clear them all.
Naturally, this would have to be done before you load any other scripts.

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • Thanks, but it's not the case. The interval has been set somewhere inside the loaded script. Maybe there are more that one `setInterval`s, and I don't have their handlers. Is there anyway to stop all those `intervals` by removing the `script` tag? – Afshin Oct 15 '19 at 08:41
  • @Afshin: Nope, you need to clear the interval, removing the script-tag doesn't suffice. You could reload the page, but that's an ugly hack: window.location.reload(); But you could override the setInterval-function - see edited answer. – Stefan Steiger Oct 15 '19 at 08:43
0

To be able to use the clearInterval() method, you must use a variable when creating the interval method:

myTimer = setInterval("javascript function", milliseconds);

Then you will be able to stop the execution by calling the clearInterval() method.

clearInterval(myTimer );

Using module pattern you can Wrap your code in an IFFE to be able to use it without removing it from dom and reinitialize it with attaching it again.

const snifferModule= (function() {
  let globVariable= null;
  let globalArray= [];
  var myVar = setInterval(myTimer, 1000);

 const initialize = function(gv, ga) {
    globVariable= gv;
    globalArray= ga;
  };

 const cleanAndRun= function() {
   clearInterval(myVar);
   // rest of code
  };

return {
    initialize,
    cleanAndRun,

  };
})();
Nima Bastani
  • 185
  • 11