Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

1.1 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */

import { useEffect, useRef, useState } from "react";
import { useNumberFormatter } from "react-aria";
import useEvent from "react-use-event-hook";

/**
 * Creates a timer that counts returns the time in seconds.
 * Interval is 100ms.
 */
export function useTimer() {
  const [time, setTime] = useState(0);
  const interval = useRef<number>(undefined);

  // one decimal place, exactly
  const numberFormatter = useNumberFormatter({
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  });

  const start = useEvent(() => {
    interval.current = window.setInterval(() => {
      setTime((time) => time + 0.1);
    }, 100);
  });

  const stop = useEvent(() => {
    if (interval.current != null) {
      window.clearInterval(interval.current);
      interval.current = undefined;
    }
  });

  const clear = useEvent(() => {
    setTime(0);
  });

  // Clear on unmount
  useEffect(() => {
    return () => {
      window.clearInterval(interval.current);
    };
  }, []);

  return {
    time: numberFormatter.format(time),
    start,
    stop,
    clear,
  };
}