I had the same question, but there seems to be no built-in solution, so here is a short workaround that I hit together:
function setScopedInterval(func, millis, scope) { return setInterval(function () { func.apply(scope); }, millis); }
using:
function MyClass() { this.timer = null; this.myFunc = function() { console.log('do some stuff'); }; this.run = function() { this.timer = setScopedInterval(function () { this.myFunc(); }, 1000, this); }; this.stop = function() { clearInterval(this.timer); }; } var instance = new MyClass(); instance.run();
This only applies to the use case in which you pass the actual function, not the line of code that needs to be executed.
As for your question about memory leak when using this function, it is not so much a problem with using setInterval , but with anonymous functions in itself. If you use a link to an object inside a lambda, that link will contain the link object in memory as long as there is an anonymous function. I think the function is destroyed by calling clearInterval .
I do not think that there is an advantage in assigning a function to a variable first, on the contrary, it will create another variable containing a link that will not be garbage collected while the anon function exists ...
source share