0

How do you clear an anonymous setInterval function, like the following, so that i stops incrementing?

var i = 0;
setInterval(function(){
    console.log(i);
    i++;
 }, 1000);



Evan
  • 55
  • 9
  • 4
    You can't. You have to store a ref to the handle. – Jared Smith Feb 08 '19 at 18:51
  • Possible duplicate of [How do I clear this setInterval inside a function?](https://stackoverflow.com/questions/2901108/how-do-i-clear-this-setinterval-inside-a-function) – KevBot Feb 08 '19 at 18:52
  • 1
    Possible duplicate of [clearTimeout without ID](https://stackoverflow.com/questions/4433926/cleartimeout-without-id) – chazsolo Feb 08 '19 at 18:52
  • May I ask why can't you simply do `var task = setInterval(...` and then `clearInterval(task)`? – Renato Byrro Feb 08 '19 at 18:53
  • I realize that you can do ```var task = setInterval(...)```. However, I'm asking if this can be done without setting it equal to some variable. The reason being I have an old JS file with an anonymous setInterval, and I cannot easily change that old JS file. – Evan Feb 08 '19 at 18:57

2 Answers2

0

You need to store it in variable and then pass that variable in clearInterval.

var i = 0;
let variable = setInterval(function(){
    i++;
    console.log(i)
 }, 1000);
//to clear interval after 5 seconds to check if it works
setTimeout(() => clearInterval(variable),5000)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

This is highly NOT recommended!

Nevertheless, you can accomplish this by temporarily monkey-patching the window.setInterval function so you can capture the reference to the timer.

The following is a consolidated example, see further below for an implementation example.

// Declare a variable to store the interval
let rogueInterval = null;

//Override the setInterval method
const oldSetInterval = window.setInterval;
window.setInterval = (...args) => {
  rogueInterval = oldSetInterval(...args);
}


var i = 0;
setInterval(function() {
  console.log(i);
  i++;
}, 1000);


// Reset it
window.setInterval = oldSetInterval;


// Will clear your rogueInterval after 5 seconds
setTimeout(() => {
  clearInterval(rogueInterval);
}, 5000);

It sounds like you are including a script via script.src, therefore, you would need to put an inline script tag before to override the setInterval, and an inline script tag after to reset the setInterval:

<script> // JS that overrides the setInterval </script>

<script src="problem-file.js"></script>

<script> // JS that resets the setInterval </script>

Unfortunately, this approach assumes there is only one setInterval within the problem file, and the setInterval is not set asynchronously itself. If you absolutely needed to, you could leave the monkey-patch in place, and check the stringified version of the function being passed in, and if it matches some criteria, then capture it.

KevBot
  • 17,900
  • 5
  • 50
  • 68