You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
997 B
JavaScript
50 lines
997 B
JavaScript
'use strict';
|
|
|
|
const Promise = require("bluebird");
|
|
const createEventEmitter = require("create-event-emitter");
|
|
|
|
const clampZero = require("./clamp-zero");
|
|
|
|
module.exports = function promiseSetInterval(callback, interval, options = {}) {
|
|
let lastInvocation = Date.now();
|
|
let timeout;
|
|
|
|
let emitter = createEventEmitter({
|
|
cancel: function cancelInterval() {
|
|
clearTimeout(timeout);
|
|
}
|
|
});
|
|
|
|
function scheduleNext() {
|
|
let delta = Date.now() - lastInvocation;
|
|
let timeout = clampZero(interval - delta);
|
|
|
|
scheduleInvocation(timeout);
|
|
}
|
|
|
|
function scheduleInvocation(nextTimeout) {
|
|
timeout = setTimeout(() => {
|
|
Promise.try(() => {
|
|
lastInvocation = Date.now();
|
|
return callback();
|
|
}).then(() => {
|
|
scheduleNext();
|
|
}).catch((err) => {
|
|
emitter.emit("error", err);
|
|
|
|
if (!options.abortOnError) {
|
|
scheduleNext();
|
|
}
|
|
});
|
|
}, nextTimeout);
|
|
}
|
|
|
|
if (options.startImmediately) {
|
|
scheduleInvocation(0);
|
|
} else {
|
|
scheduleNext();
|
|
}
|
|
|
|
return emitter;
|
|
};
|