Reputation: 16055
I've created this little object that's pretty handy when it comes to intervals and works pretty good as an animation frame, but it has this little thing about it. If the reference to the instance is lost, the interval keeps going.
function Interval(callback, interval){
var timer = null;
this.start = function(){
if(!timer) timer = setInterval(callback, interval);
};
this.stop = function(){
clearInterval(timer);
timer = null;
};
this.changeSpeed = function(a){
interval = a;
this.stop();
this.start();
}
this.destroy = function(){
delete this;
}
}
Obviously if javascript has no destruct method I can't track when to stop the interval, so I figured I should create a destroy method, but I'm not really sure if I can destroy the instance from within the object. It makes sense but... Any help is appreciated!
Upvotes: 4
Views: 2847
Reputation: 45155
How about doing something like this:
function Interval(callback, interval){
var self = this;
var timer = null;
this.start = function(){
if(!timer) timer = setInterval(function() {
callback(self)
}, interval);
};
this.stop = function(){
clearInterval(timer);
timer = null;
};
this.changeSpeed = function(a){
interval = a;
this.stop();
this.start();
}
this.destroy = function(){
this.stop();
}
}
Now at least when the callback is called it will pass a reference to the your object and the callback will at least have a chance to stop it if they don't need it anymore.
The trick here is to use a closure to ensure you can still reference the object when the interval expires (hence the self
variable).
So now I could do something like this:
var foo = new Interval(function(i) {
// check if my interval is still needed
if (dontNeedItAnymore) {
i.destroy(); // or just .stop()
}
else {
// do whatever
}
}, 1000);
foo = null; // whoops, lost the reference, but the callback will still be able to reference it
Upvotes: 2