Reputation: 1436
If I'm writing javascript that contains a lot of intervals, I tend to keep track of them in a array of interval objects
function Interval(id, desc){
this.id = id;
this.desc = desc;
}
prototypes etc....
Then I create my interval functions with something like
intervalArray.push(new Interval(setInterval(function, milli),"Demo interval"))
I know this is verging on OCD, but trust me, it has made problem solving easier as it's simpler to keep track of the wretched things at the dev tools prompt when you want to clearInterval on one or two of them when running.
So the question...
Given an interval id, is there any way to access its current status?
ie if I have an interval x set to a repeat time of 300000 to fire every five minutes, is there any way to get x.timer, a function that, after one minute would return 60000?
A couple of times now, while debugging, it would have been useful to know how close a given interval was to firing.
I guess I could add another value to my interval object - .lastFired, initiate it with 0 and update it with a timestamp when it fires off but presumably the browser keeps track of intervals somewhere...
Upvotes: 3
Views: 3343
Reputation: 3848
You may extend your Interval Function further:
function Interval(fn, desc, ms){
this.desc = desc;
this.status = -1;
var that = this;
this.id = window.setInterval(function () {
// save some progess to the Interval object
// that is used, because in interval callback this === window
that.status++;
// now call your function fn, using this === Interval object
fn.call(that);
}, ms);
this.stop = function () {
if (this.id) {
window.clearInterval(this.id);
this.id = 0;
this.status = -1;
}
};
}
// Usage:
var myInterval = new Interval(function () {
// frequent action
// this === Interval object instance
if (this.status === 5) this.stop();
}, "description", 10000);
Now you could also create an onprogress event handler like callback, to get notified if your progress changed. You also may move the this.id = window.setInterval(...
statement into a this.start = function () {
public function, to start and stop later.
Upvotes: 3
Reputation: 71918
The browser schedules the callback to run when the interval expires. At every "tick" of its internal event loop, it checks if any interval has already expired. If so, its callback is invoked. Exactly how browsers keep track of the interval is up to the implementation, but no indicator of how long it will wait before invoking the callback is exposed. So no. :(
Upvotes: 1