DEV Community

Cover image for Simple Stopwatch in plain JS
artydev
artydev

Posted on • Updated on

Simple Stopwatch in plain JS

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

Top comments (2)

Collapse
 
tao_xin_23db52b1401921dcb profile image
Tao Xin (vanjs.org)

Thanks for sharing the example. Have you considered adding this example to your VanJS series: dev.to/artydev/series/23075?

Collapse
 
artydev profile image
artydev

Done :-)
Thank you Tao