Simple Stopwatch in plain JS

artydev - May 25 '23 - - Dev Community

Here is a simple stopwatch, adapted from VanJS doc.

Demo

As you can see, nothing complicated, plain JS, no hooks, no bundling, all this under 1.2kB of library !!!


const {button,span, div, pre, h1} = van.tags

const elapsed = van.state("0.00")

const Stopwatch = () => {
  let id;
  const start = () => id = id || setInterval(() =>
    elapsed.val = (Number(elapsed.val) + 0.01).toFixed(2), 10)
  return span(
    button({onclick: start}, "Start"),
    button({onclick: () => (clearInterval(id), id = 0)}, "Stop"),
    button({onclick: () =>
      (clearInterval(id), id = 0, elapsed.val = "0.00")}, "Reset"),
  )
}

const Screendisplay = () =>  h1(elapsed, " s")

van.add(app, div(
  h1("A Simple Stopwatch"),
  div ({class:"stopwatch"},
    div({class:"content"},
      Screendisplay(),
      Stopwatch())      
    )
  )
)
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player