hydrogen-web/src/utils/DOMClock.js

53 lines
1 KiB
JavaScript
Raw Normal View History

import {AbortError} from "./error.js";
class DOMTimeout {
constructor(ms) {
this._reject = null;
2020-04-05 18:41:15 +05:30
this._handle = null;
this._promise = new Promise((resolve, reject) => {
this._reject = reject;
2020-04-05 18:41:15 +05:30
this._handle = setTimeout(() => {
this._reject = null;
resolve();
}, ms);
});
}
2020-04-05 18:41:15 +05:30
elapsed() {
return this._promise;
}
abort() {
if (this._reject) {
this._reject(new AbortError());
2020-04-05 18:41:15 +05:30
clearTimeout(this._handle);
this._handle = null;
this._reject = null;
}
}
}
class DOMTimeMeasure {
constructor() {
this._start = window.performance.now();
}
measure() {
return window.performance.now() - this._start;
}
}
export class DOMClock {
createMeasure() {
return new DOMTimeMeasure();
}
createTimeout(ms) {
return new DOMTimeout(ms);
}
now() {
return Date.now();
}
}