mirror of
https://github.com/livebook-dev/livebook.git
synced 2024-11-17 05:18:52 +08:00
41 lines
791 B
JavaScript
41 lines
791 B
JavaScript
import { getAttributeOrThrow } from "../lib/attribute";
|
|
|
|
const UPDATE_INTERVAL_MS = 100;
|
|
|
|
/**
|
|
* A hook used to display a timer counting from the moment
|
|
* of mounting.
|
|
*/
|
|
const Timer = {
|
|
mounted() {
|
|
this.props = getProps(this);
|
|
|
|
this.state = {
|
|
start: new Date(this.props.start),
|
|
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`;
|
|
},
|
|
};
|
|
|
|
function getProps(hook) {
|
|
return {
|
|
start: getAttributeOrThrow(hook.el, "data-start"),
|
|
};
|
|
}
|
|
|
|
export default Timer;
|