Add an error handler parameter to intervals

This commit is contained in:
Leonid Logvinov 2018-01-10 13:50:26 +01:00
parent 1f5dfd71d5
commit 065570ebf5
No known key found for this signature in database
GPG Key ID: 0DD294BFDE8C95D4

View File

@ -1,14 +1,18 @@
import * as _ from 'lodash';
export const intervalUtils = {
setAsyncExcludingInterval(fn: () => Promise<void>, intervalMs: number) {
setAsyncExcludingInterval(fn: () => Promise<void>, intervalMs: number, onError: (err: Error) => void) {
let locked = false;
const intervalId = setInterval(async () => {
if (locked) {
return;
} else {
locked = true;
try {
await fn();
} catch (err) {
onError(err);
}
locked = false;
}
}, intervalMs);
@ -17,4 +21,17 @@ export const intervalUtils = {
clearAsyncExcludingInterval(intervalId: NodeJS.Timer): void {
clearInterval(intervalId);
},
setInterval(fn: () => void, intervalMs: number, onError: (err: Error) => void) {
const intervalId = setInterval(() => {
try {
fn();
} catch (err) {
onError(err);
}
}, intervalMs);
return intervalId;
},
clearInterval(intervalId: NodeJS.Timer): void {
clearInterval(intervalId);
},
};