type Milliseconds = number;
type Seconds = number;

type Timestamp = {
  start: Milliseconds;
  end: Milliseconds;
  duration: Milliseconds;
};

type Timestamps = Record<string, Timestamp>;

let timestamps: Timestamps = {};

const record = (name) => {
  if (timestamps[name]) {
    return;
  }

  timestamps[name] = {
    start: Date.now(),
    end: 0,
    duration: 0,
  };
};

const over = (name) => {
  if (!timestamps[name]) {
    return;
  }

  const { start } = timestamps[name];
  const end = Date.now();
  const duration = end - start;

  timestamps[name] = {
    start,
    end,
    duration,
  };
};

const calculateTotal = () => {
  Object.keys(timestamps).reduce((total, currKey) => {
    const { duration } = timestamps[currKey];
    return (total += duration);
  }, 0);
};

用法:

record('init')
over('init');

热饭班长
3.7k 声望434 粉丝

先去做,做出一坨狗屎,再改进。