Path: blob/main/core/wasi-js/src/bindings/browser-hrtime.ts
1067 views
/*1This is https://github.com/cabinjs/browser-hrtime/blob/master/src/index.ts2but modified to not use window, since I want to use this in a WebWorker.3Upstream is MIT license.45This also doesn't define any global variables.6*/78const _perfomancePolyfill = () => {9// based on https://gist.github.com/paulirish/5438650 copyright Paul Irish 2015.10if (!("performance" in self)) {11(self as any).performance = {};12}1314Date.now =15Date.now ||16(() => {17// thanks IE818return new Date().getTime();19});2021if ("now" in self.performance === false) {22let nowOffset = Date.now();2324if (performance.timing && performance.timing.navigationStart) {25nowOffset = performance.timing.navigationStart;26}2728self.performance.now = () => Date.now() - nowOffset;29}30};3132const _hrtime = (previousTimestamp?: [number, number]): [number, number] => {33_perfomancePolyfill();34const baseNow = Math.floor((Date.now() - performance.now()) * 1e-3);35const clocktime = performance.now() * 1e-3;36let seconds = Math.floor(clocktime) + baseNow;37let nanoseconds = Math.floor((clocktime % 1) * 1e9);3839if (previousTimestamp) {40seconds = seconds - previousTimestamp[0];41nanoseconds = nanoseconds - previousTimestamp[1];42if (nanoseconds < 0) {43seconds--;44nanoseconds += 1e9;45}46}47return [seconds, nanoseconds];48};49const NS_PER_SEC: number = 1e9;50_hrtime.bigint = (time?: [number, number]): bigint => {51const diff = _hrtime(time);52return (diff[0] * NS_PER_SEC + diff[1]) as unknown as bigint;53};54export default _hrtime;555657