2021-12-03 21:23:50 +08:00
|
|
|
import { getAttributeOrThrow } from "../lib/attribute";
|
|
|
|
|
2021-06-20 23:06:30 +08:00
|
|
|
const UPDATE_INTERVAL_MS = 100;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A hook used to display a timer counting from the moment
|
|
|
|
* of mounting.
|
|
|
|
*/
|
|
|
|
const Timer = {
|
|
|
|
mounted() {
|
2021-12-03 21:23:50 +08:00
|
|
|
this.props = getProps(this);
|
|
|
|
|
2021-06-20 23:06:30 +08:00
|
|
|
this.state = {
|
2021-12-03 21:23:50 +08:00
|
|
|
start: new Date(this.props.start),
|
2021-06-20 23:06:30 +08:00
|
|
|
interval: null,
|
|
|
|
};
|
|
|
|
|
|
|
|
this.state.interval = setInterval(() => {
|
|
|
|
this.__tick();
|
|
|
|
}, UPDATE_INTERVAL_MS);
|
|
|
|
},
|
|
|
|
|
|
|
|
destroyed() {
|
|
|
|
clearInterval(this.state.interval);
|
|
|
|
},
|
|
|
|
|
|
|
|
__tick() {
|
|
|
|
const elapsedMs = Date.now() - this.state.start;
|
|
|
|
const elapsedSeconds = elapsedMs / 1_000;
|
|
|
|
|
|
|
|
this.el.innerHTML = `${elapsedSeconds.toFixed(1)}s`;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2021-12-03 21:23:50 +08:00
|
|
|
function getProps(hook) {
|
|
|
|
return {
|
|
|
|
start: getAttributeOrThrow(hook.el, "data-start"),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-06-20 23:06:30 +08:00
|
|
|
export default Timer;
|