0

Lets say we have this code that I don't have access to/ I cannot change.

function f() {
// bad tasks
}
setInterval(f, 10000);

I want to modify function f so I write something like this underneath.

window.f = function(){
// good tasks
}

But the original function f() with bad tasks in it are still running every 10 seconds. Seems like the function passed into setInterval is still pointing to the original function. How do I stop it?

Noob
  • 1

3 Answers3

1

Your assumption is correct: the interval keeps a reference to the original f.

There is no way to change this without editing the original script. All you can do is clear all intervals on the site and start another interval. See https://stackoverflow.com/a/8860203/27862 for that.

Community
  • 1
  • 1
user123444555621
  • 148,182
  • 27
  • 114
  • 126
0

One way:

function f() {
    //bad tasks
}

setInterval(function() { f(); }, 10000);

window.f = function() {
    //good tasks
}

so that timer will call not the old f() passed to it but rather a function named f at the moment.

Other way:

function f() {
    //bad tasks
}

var interval = setInterval(f, 10000);

function g() {
    //good tasks
}

clearInterval(interval);
setInterval(g, 10000);
penartur
  • 9,792
  • 5
  • 39
  • 50
  • Seeing the question, I don't think Noob is able to change the `setInterval` part. – Yoshi Apr 18 '12 at 06:53
  • Your first way do not work (tested). Second way cannot work for Noob because _code that I don't have access to/ I cannot change_ and Noob cannot clear old interval. – Andrew D. Apr 18 '12 at 07:10
  • @AndrewD. If Noob is willing to clear all current intervals, he could kill the interval in question (just loop from 0 to the next interval-id from `setInterval` and clear every interval ;)) – Yoshi Apr 18 '12 at 07:12
  • @AndrewD. could you please say how did you tested it? It works on my configuration: https://gist.github.com/2411806 . It won't help Noob, as Yoshi explained, but it should work nevertheless. – penartur Apr 18 '12 at 07:46
  • @penartur, I want say that `setInterval (function () {f ();}, 10000),` does not replace the original `setInterval(f, 10000); ' and cannot help. – Andrew D. Apr 18 '12 at 10:26
  • @AndrewD. I meant modifying the existing code (so that instead of `f` itself the closure on `f` will be passed to `setInterval`, which will allow changing `f` in the outer scope). – penartur Apr 18 '12 at 11:55
0

Don't use setInterval, use setTimeout instead. It will give you the control you need.

function f() {
 // bad tasks
 fTimeout = setTimeout(f,1000);
}
//start
var fTimeout = setTimeout(f,1000);

now if something bad is going on and you want to rewrite f:

clearTimeout(fTimeout);
window.f = function() { 
            /* good stuff */ 
            fTimeout = setTimeout(f,1000);
           }
fTimeout = setTimeout(f,1000);

See also

KooiInc
  • 119,216
  • 31
  • 141
  • 177