Add clearTimeout() implementation to Bluebird
Necessary for cancellable promises
This commit is contained in:
parent
03da4a9d52
commit
aa70e60fc6
|
@ -35,19 +35,19 @@
|
||||||
// Set BackstagePass (which contains .Error, etc.) as global object
|
// Set BackstagePass (which contains .Error, etc.) as global object
|
||||||
self = this;
|
self = this;
|
||||||
|
|
||||||
// Provide an implementation of setTimeout
|
|
||||||
self.setTimeout = new function() {
|
|
||||||
// We need to maintain references to running nsITimers. Otherwise, they can
|
// We need to maintain references to running nsITimers. Otherwise, they can
|
||||||
// get garbage collected before they fire.
|
// get garbage collected before they fire. Also, we might need to cancel them.
|
||||||
var _runningTimers = [];
|
var _runningTimers = {};
|
||||||
|
|
||||||
return function setTimeout(func, ms) {
|
// Provide an implementation of setTimeout
|
||||||
|
self.setTimeout = function (func, ms) {
|
||||||
|
var id = Math.floor(Math.random() * (1000000000000 - 1)) + 1
|
||||||
var useMethodjit = Components.utils.methodjit;
|
var useMethodjit = Components.utils.methodjit;
|
||||||
var timer = Components.classes["@mozilla.org/timer;1"]
|
var timer = Components.classes["@mozilla.org/timer;1"]
|
||||||
.createInstance(Components.interfaces.nsITimer);
|
.createInstance(Components.interfaces.nsITimer);
|
||||||
timer.initWithCallback({"notify":function() {
|
timer.initWithCallback({"notify":function() {
|
||||||
// Remove timer from array so it can be garbage collected
|
// Remove timer from object so it can be garbage collected
|
||||||
_runningTimers.splice(_runningTimers.indexOf(timer), 1);
|
delete _runningTimers[id];
|
||||||
|
|
||||||
// Execute callback function
|
// Execute callback function
|
||||||
try {
|
try {
|
||||||
|
@ -73,9 +73,16 @@
|
||||||
self.debug(err.stack, 1);
|
self.debug(err.stack, 1);
|
||||||
}
|
}
|
||||||
}}, ms, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
|
}}, ms, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
|
||||||
_runningTimers.push(timer);
|
_runningTimers[id] = timer;
|
||||||
}
|
return id;
|
||||||
};
|
};
|
||||||
|
self.clearTimeout = function (id) {
|
||||||
|
var timer = _runningTimers[id];
|
||||||
|
if (timer) {
|
||||||
|
timer.cancel();
|
||||||
|
}
|
||||||
|
delete _runningTimers[id];
|
||||||
|
}
|
||||||
|
|
||||||
self.debug = function (msg) {
|
self.debug = function (msg) {
|
||||||
dump(msg + "\n\n");
|
dump(msg + "\n\n");
|
||||||
|
|
Loading…
Reference in New Issue
Block a user